From 323cd49197666cf5ce4a3ce5992ba0edbb7fd727 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:02:46 +0800 Subject: [PATCH 01/10] feat: add host plugin executor, Codex isolation and governance checks --- CHANGELOG.md | 31 ++ Documentation/Architecture/Package.md | 40 +- Documentation/Reference/ManifestSchema.md | 36 ++ Scripts/generate-manifest-schema.py | 3 + Sources/AgentsCore/AgentPluginManifest.swift | 3 + Sources/AgentsCore/AgentRegistry.swift | 25 +- Sources/AgentsCore/ComponentDeclaration.swift | 33 +- Sources/AgentsCore/ContentAuditFiles.swift | 7 +- .../AgentsCore/HostPluginConfiguration.swift | 74 ++++ Sources/AgentsCore/LedgerStateStore.swift | 6 +- .../AgentsCore/NativeTargetCoordination.swift | 6 +- Sources/AgentsCore/TransactionPaths.swift | 81 ++-- .../AgentsManifest/ManifestProjection.swift | 11 + Sources/AgentsManifest/ManifestSchema.swift | 17 +- .../Resources/agents.schema.json | 107 ++++++ .../AgentsManifest/SourceReferenceEdits.swift | 3 +- Sources/AgentsManifest/YAMLConstruction.swift | 14 + .../AgentsManifest/YAMLDomainValidation.swift | 25 ++ Sources/AgentsManifest/YAMLProjection.swift | 3 + Sources/AgentsManifest/YAMLValidation.swift | 28 +- Sources/AgentsManifest/YAMLWriter.swift | 9 +- Sources/AgentsSkills/Discovery.swift | 126 +++--- .../AgentsSkills/GovernanceDiscovery.swift | 35 ++ Sources/AgentsSkills/SkillLifecycle.swift | 6 +- .../HostPlugins/HostPluginCommandRunner.swift | 85 +++++ .../HostPlugins/HostPluginDocuments.swift | 89 +++++ .../HostPlugins/HostPluginExecutor.swift | 359 ++++++++++++++++++ .../HostPlugins/HostPluginInventory.swift | 336 ++++++++++++++++ .../HostPlugins/HostPluginModels.swift | 64 ++++ .../HostPlugins/HostPluginTarget.swift | 167 ++++++++ .../HostPlugins/SkillGovernance.swift | 310 +++++++++++++++ .../AgentsUpdates/ProducerPatchRoutes.swift | 8 +- Sources/AgentsUpdates/UpdatePlan.swift | 10 +- Sources/AgentsUpdates/UpdateReporting.swift | 59 ++- Sources/Components/ArtifactAggregation.swift | 50 ++- Sources/Components/ComponentFields.swift | 4 + .../Components/DeploymentConstruction.swift | 19 +- Sources/Components/Expansion.swift | 1 + .../Import/ImportSkillContent.swift | 5 +- .../Import/NativeContainerImport.swift | 17 + .../Import/NativeSourceImport.swift | 2 +- Sources/Components/Import/SourceImport.swift | 2 +- .../Import/SourceImportProposal.swift | 18 +- Sources/Components/LedgerPayload.swift | 3 + .../NativeGeneratedPluginLayoutV1.swift | 7 +- Sources/Components/PluginExpansion.swift | 56 ++- Sources/Components/SourceCatalog.swift | 30 +- .../AgentsCoreTests/AgentRegistryTests.swift | 12 +- .../StateTransactionTests.swift | 71 ++++ .../TransactionCostTests.swift | 2 +- .../FullDeclarationTests.swift | 44 +++ .../CodexUserIsolationTests.swift | 141 +++++++ .../DiscoveryBehaviorTests.swift | 21 + .../InstalledInventoryTests.swift | 6 +- .../RetainedLifecycleTests.swift | 11 +- .../SkillLifecycleTests.swift | 5 +- .../HostPluginExecutorTests.swift | 314 +++++++++++++++ .../SkillGovernanceTests.swift | 130 +++++++ .../ComponentsTests/SourceCatalogTests.swift | 77 ++++ Tests/StateTestProcess/main.swift | 10 + 60 files changed, 3064 insertions(+), 210 deletions(-) create mode 100644 Sources/AgentsCore/AgentPluginManifest.swift create mode 100644 Sources/AgentsCore/HostPluginConfiguration.swift create mode 100644 Sources/AgentsSkills/GovernanceDiscovery.swift create mode 100644 Sources/AgentsUpdates/HostPlugins/HostPluginCommandRunner.swift create mode 100644 Sources/AgentsUpdates/HostPlugins/HostPluginDocuments.swift create mode 100644 Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift create mode 100644 Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift create mode 100644 Sources/AgentsUpdates/HostPlugins/HostPluginModels.swift create mode 100644 Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift create mode 100644 Sources/AgentsUpdates/HostPlugins/SkillGovernance.swift create mode 100644 Tests/AgentsSkillsTests/CodexUserIsolationTests.swift create mode 100644 Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift create mode 100644 Tests/AgentsUpdatesTests/SkillGovernanceTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 3935eb8..742c693 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,37 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## 0.4.0 + +### Added + +- Support `kind: hostPlugin` declarations for Codex, Claude Code, and Antigravity + in `agents.yaml` with explicit recipient validation and manifest schema + generation. +- Add `HostPluginExecutor` in `AgentsUpdates` for read-only filesystem + inspection and preview (`inspect`, `preview`) plus explicit, lock-external host + plugin synchronization (`sync(apply:)`), using `OwnedDuplexProcess` with closed + stdin, bounded timeouts, and mandatory filesystem readback after every command. +- Add `SkillGovernance.inspect` in `AgentsUpdates` for deterministic doctor + checks covering host plugin drift, unmanaged legacy Codex shared-root symlinks, + realpath-resolved plugin-vs-standalone skill collisions, and per-host UTF-8 + always-visible skill listing estimates (supporting + `SLASH_COMMAND_TOOL_CHAR_BUDGET` for Claude Code). +- Recognize portable root `plugin.json` manifests declaring the exact Agent + Plugins 1.0 `$schema`, coalesce dual `.claude-plugin/plugin.json` + root + `plugin.json` bundles into a single catalog entry, and discover skills through + `.agents/plugins/marketplace.json`. + +### Changed + +- Route new user-scope Codex skill deployments to `$CODEX_HOME/skills` + (`~/.codex/skills`) under a dedicated `skills-codex-private` ledger root while + preserving historical `skills-codex` ledger/journal semantics for safe + ownership-checked migration without taking over unmanaged private destinations + or removing shared leaves owned by other agents. +- Include `~/.agents/skills` in `AgentRegistry.nativeUserScanDirectories` for + Antigravity. + ## 0.3.1 ### Fixed diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 1f463c8..277e4ad 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -131,8 +131,14 @@ manifest and its project scope. `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. + project root, home directory and environment. New Codex user deployments use + `$CODEX_HOME/skills` (default `~/.codex/skills`). The `skills-codex-private` + ledger root and `codex-private` journal root identify that location. + User-scope `skills-codex` ledger entries and `codex` journal paths continue + to identify `~/.agents/skills`, which Antigravity also scans. Migration + verifies legacy ownership and destination availability, and retains a shared + leaf while another deployment owns it. Recipients that share a physical + destination agree on install mode. - `FileHash` hashes tree entries, hidden files and symlink destinations; `PathSafety` checks paths and creates filesystem skill identities. @@ -439,13 +445,41 @@ empty containers. Opaque registration requires the exact container name from ada 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- +and separate producer selection claims. The Agent Plugins 1.0 manifest schema +identifies a portable root `plugin.json`. When a bundle also has a Claude +manifest, components mode uses the Claude document once and validates agreement +between the declared names. 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 +`HostPluginExecutor.inspect` and `preview` use the runtime's local filesystem +and NativeDocuments to observe host installations and report exact command +arguments and settings changes. `sync(apply: true)` executes vendor commands +outside scope and shared-resource locks. It observes host state after each +command, including failures and timeouts. Codex toggles use fresh TOML bytes +under the existing Codex config coordination routes. Antigravity project +registration edits the workspace discovery manifest under the project lock. +Claude Code uses host commands with its selected user, project, or local scope. + +The manifest's `hostPlugin` declaration takes explicit recipients and either +a marketplace ID or one source-backed bundle. Source-backed inspection reads a +local checkout and uses the host's catalog identity where required. Host +installation and enablement are reconciled with the vendor's records. +The combined update graph continues to freeze and replay `kind: plugin` +through its existing resource and transaction path. + +`SkillGovernance.inspect` compares declared host plugin state with observed +installation and enablement, and checks the merged project and user scan roots +against effectively enabled plugin skills. Collisions report parsed names and +physical file identity. Its advisory budgets estimate the UTF-8 bytes of +deduplicated names and descriptions, excluding per-skill framing and host +built-ins. The default advisory threshold is 8,000. Claude Code can supply a +threshold through `SLASH_COMMAND_TOOL_CHAR_BUDGET`. The optional budgets are +omitted when there are no skills or recovery is pending. + `MCPRegistry` reads MCP Registry v0.1 pages and exact server versions. Request credentials stay in the registry's in-memory HTTP transport. Each returned choice captures a portable configuration. Selection admits explicit recipients through diff --git a/Documentation/Reference/ManifestSchema.md b/Documentation/Reference/ManifestSchema.md index 7478ec6..35be20a 100644 --- a/Documentation/Reference/ManifestSchema.md +++ b/Documentation/Reference/ManifestSchema.md @@ -601,6 +601,34 @@ Declare a plugin resource for native installation or component expansion. | `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_hostPluginID + +Declare a plugin for explicit host synchronization. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `hostPlugin` | Selects a plugin managed by an explicit host synchronization. | +| `name` | yes | string | Symbolic name of the declaration. | +| `agents` | yes | sequence of agent (at most 10000 items) | Explicit recipients. A marketplace ID requires one recipient. A bundle requires at least one. | +| `enabled` | | boolean | Desired host enablement. Omission defaults to true. | +| `claudeScope` | | `user` / `project` / `local` | Claude Code scope. Omission uses the selected agents scope. | +| `pluginId` | yes | string | Host plugin ID. | +| `marketplace` | | string | Optional marketplace URL or path. | + +## component_hostPluginBundle + +Declare a plugin for explicit host synchronization. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `hostPlugin` | Selects a plugin managed by an explicit host synchronization. | +| `name` | yes | string | Symbolic name of the declaration. | +| `agents` | yes | sequence of agent (at most 10000 items) | Explicit recipients. A marketplace ID requires one recipient. A bundle requires at least one. | +| `enabled` | | boolean | Desired host enablement. Omission defaults to true. | +| `claudeScope` | | `user` / `project` / `local` | Claude Code scope. Omission uses the selected agents scope. | +| `source` | yes | string | Source alias containing the plugin bundle. | +| `path` | yes | string | Relative path to one plugin directory. | + ## component 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. @@ -645,6 +673,14 @@ component_ignore component_plugin +### Alternative 11 + +component_hostPluginID + +### Alternative 12 + +component_hostPluginBundle + ## use 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. diff --git a/Scripts/generate-manifest-schema.py b/Scripts/generate-manifest-schema.py index 4235712..c6182ff 100644 --- a/Scripts/generate-manifest-schema.py +++ b/Scripts/generate-manifest-schema.py @@ -78,6 +78,9 @@ def allow(keys): raise ValueError('enum must contain unique strings') return '.enumeration([' + ', '.join(q(x) for x in choices) + '])' kind = value.get('type') + if kind == 'boolean': + allow({'type'}) + return '.boolean' if kind == 'string': allow({'type'}) return '.string' diff --git a/Sources/AgentsCore/AgentPluginManifest.swift b/Sources/AgentsCore/AgentPluginManifest.swift new file mode 100644 index 0000000..3b1759f --- /dev/null +++ b/Sources/AgentsCore/AgentPluginManifest.swift @@ -0,0 +1,3 @@ +package enum AgentPluginManifest { + package static let schema = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json" +} diff --git a/Sources/AgentsCore/AgentRegistry.swift b/Sources/AgentsCore/AgentRegistry.swift index 7ae8bc0..d09e6d3 100644 --- a/Sources/AgentsCore/AgentRegistry.swift +++ b/Sources/AgentsCore/AgentRegistry.swift @@ -145,7 +145,7 @@ package enum AgentRegistry { return projectSkillsDirectory(for: agent, environment: environment).standardizedFileURL.path == canonical case .user: - return agent != .antigravity + return agent != .antigravity && agent != .codex && usesUniversalProjectSkillsDirectory(for: agent, environment: environment) } } @@ -159,6 +159,25 @@ package enum AgentRegistry { return skillsDirectory(for: agent, scope: scope, environment: environment) } + package static func skillRootKey(for agent: AgentID, scope: InstallScope) -> String { + "skills-" + (scope == .user && agent == .codex ? "codex-private" : agent.rawValue) + } + + package static func skillRoot( + _ key: String, scope: InstallScope, environment: RuntimeEnvironment + ) -> (agent: AgentID, directory: URL)? { + if scope == .user && key == "skills-codex-private" { + return (.codex, userSkillsDirectory(for: .codex, environment: environment)) + } + guard key.hasPrefix("skills-"), let agent = AgentID(rawValue: String(key.dropFirst(7))), + agent.supportsSkills + else { return nil } + if scope == .user && agent == .codex { + return (agent, canonicalSkillsDirectory(scope: scope, environment: environment)) + } + return (agent, installSkillsDirectory(for: agent, scope: scope, environment: environment)) + } + package static func projectSkillsDirectory(for agent: AgentID, environment: RuntimeEnvironment) -> URL { @@ -205,15 +224,13 @@ package enum AgentRegistry { for agent: AgentID, environment: RuntimeEnvironment ) -> [URL] { switch agent { - case .codex, .cursor, .geminiCLI, .opencode: + case .codex, .cursor, .geminiCLI, .opencode, .antigravity: return [ userSkillsDirectory(for: agent, environment: environment), environment.homeDirectory.appendingPathComponent(".agents/skills"), ] case .claudeCode: return [userSkillsDirectory(for: agent, environment: environment)] - case .antigravity: - return [userSkillsDirectory(for: agent, environment: environment)] } } diff --git a/Sources/AgentsCore/ComponentDeclaration.swift b/Sources/AgentsCore/ComponentDeclaration.swift index 3887601..b27f5f4 100644 --- a/Sources/AgentsCore/ComponentDeclaration.swift +++ b/Sources/AgentsCore/ComponentDeclaration.swift @@ -158,9 +158,37 @@ public enum PluginModeDeclaration: String, Equatable, Sendable { case components } +public enum ClaudePluginScope: String, Codable, Equatable, Sendable { + case user, project, local +} + +public enum HostPluginSelector: Equatable, Sendable { + case marketplace(pluginId: String, marketplace: String? = nil) + case bundle(source: String, path: String) +} + +public struct HostPluginDeclaration: Equatable, Sendable { + public var name: String + public var selector: HostPluginSelector + public var agents: [AgentID] + public var enabled: Bool + public var claudeScope: ClaudePluginScope? + + public init( + name: String, selector: HostPluginSelector, agents: [AgentID], enabled: Bool = true, + claudeScope: ClaudePluginScope? = nil + ) { + self.name = name + self.selector = selector + self.agents = agents + self.enabled = enabled + self.claudeScope = claudeScope + } +} + public enum DeclaredComponentKind: String, CaseIterable, Codable, Hashable, Sendable { case skills, instructions, mcpServer, hook, subagent, command, lspServer, permissions, ignore, - plugin + plugin, hostPlugin } public enum ComponentReferenceDeclaration: Equatable, Sendable { @@ -323,6 +351,8 @@ public enum ComponentDeclaration: Equatable, Sendable { agents: [AgentID]? = nil, condition: DeclarationCondition? = nil, native: NativeConfiguration = [:]) + case hostPlugin(HostPluginDeclaration) + public var kind: DeclaredComponentKind { switch self { case .skills: .skills @@ -335,6 +365,7 @@ public enum ComponentDeclaration: Equatable, Sendable { case .permissions: .permissions case .ignore: .ignore case .plugin: .plugin + case .hostPlugin: .hostPlugin } } } diff --git a/Sources/AgentsCore/ContentAuditFiles.swift b/Sources/AgentsCore/ContentAuditFiles.swift index 1c30d8c..34d617a 100644 --- a/Sources/AgentsCore/ContentAuditFiles.swift +++ b/Sources/AgentsCore/ContentAuditFiles.swift @@ -197,11 +197,8 @@ extension StateStore { root = environment.projectDirectory } else if key == InstructionLocations.ruleRoot(in: scope) { root = InstructionLocations.antigravityAuthority(environment, scope: scope).logicalDirectory - } else if key.hasPrefix("skills-"), let agent = AgentID(rawValue: String(key.dropFirst(7))), - agent.supportsSkills - { - root = AgentRegistry.installSkillsDirectory( - for: agent, scope: scope, environment: environment) + } else if let skill = AgentRegistry.skillRoot(key, scope: scope, environment: environment) { + root = skill.directory } else if key.hasPrefix("instructions-"), let agent = AgentID(rawValue: String(key.dropFirst("instructions-".count))) { diff --git a/Sources/AgentsCore/HostPluginConfiguration.swift b/Sources/AgentsCore/HostPluginConfiguration.swift new file mode 100644 index 0000000..1dda3ff --- /dev/null +++ b/Sources/AgentsCore/HostPluginConfiguration.swift @@ -0,0 +1,74 @@ +import Foundation + +/// Settings edits coordinate with the same physical writers as native component updates. +package enum HostPluginConfigurationRoute { + case codex, antigravityProject + + package func edit( + store: StateStore, maximumFileBytes: Int, transform: (Data?) throws -> Data? + ) throws { + let codexRoute: NativeTargetRoute = store.scope == .user ? .codexMCPUser : .codexMCPProject + let routes: Set = self == .codex ? [codexRoute] : [] + try store.withLock(footprint: routes) { + let destination: URL + switch self { + case .codex: + destination = try store.nativeTarget(for: codexRoute).url + case .antigravityProject: + guard store.scope == .project else { throw CoreError.unsafePath("expected project scope") } + let root = NativeRootAuthority( + loader: store.environment.projectDirectory, descendants: [".agents"]) + destination = try root.physicalDirectory().appendingPathComponent("plugins.json") + try store.requireProjectNativeAuthority(at: destination) + } + try edit(destination, maximumFileBytes: maximumFileBytes, transform: transform) + } + } + + private func edit( + _ destination: URL, maximumFileBytes: Int, transform: (Data?) throws -> Data? + ) throws { + let before = try TargetPrecondition.readingFile(destination, maximumFileBytes: maximumFileBytes) + guard let after = try transform(before.bytes), after != before.bytes else { return } + let parentURL = destination.deletingLastPathComponent() + let parent = try DirectoryHandle(at: parentURL, create: true) + let name = destination.lastPathComponent + let staging = ".host-plugin-" + UUID().uuidString + let temporary = try parent.makeDirectory(staging, syncParent: false) + let temporaryIdentity = try temporary.objectIdentity + var cleanStaging = true + defer { + if cleanStaging { try? parent.remove(staging, identity: temporaryIdentity) } + } + try temporary.write( + name, data: after, preservingMetadataOf: before.evidence.exists ? name : nil, + originalParent: parent, syncParent: false) + try before.evidence.validate() + guard try DirectoryHandle(at: parentURL).objectIdentity == parent.objectIdentity else { + throw CoreError.invalidState("host configuration parent changed") + } + if !before.evidence.exists { + try temporary.move(name, to: parent, named: name, mode: .exclusive) + return + } + let candidate = try FileSnapshot.capture( + name, from: temporary, maximumFileBytes: maximumFileBytes) + try temporary.atomicRename(name, to: parent, named: name, mode: .exchange) + .requireSuccess("replace host plugin configuration") + cleanStaging = false + // Restore the displaced object even if it is no longer a readable configuration file. + if let displaced = try? FileSnapshot.capture( + name, from: temporary, maximumFileBytes: maximumFileBytes), + displaced.snapshot == before.evidence.snapshot + { + cleanStaging = true + try parent.sync() + return + } + if try parent.info(name).map({ FileObjectIdentity($0) }) == candidate.snapshot?.identity { + try temporary.move(name, to: parent, named: name, mode: .exchange) + cleanStaging = true + } + throw CoreError.invalidState("host configuration changed during publication") + } +} diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift index fe3cbc1..20a9652 100644 --- a/Sources/AgentsCore/LedgerStateStore.swift +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -45,8 +45,10 @@ extension StateStore { roots[NativeTargetRoute.globalRoot] = roots[NativeTargetRoute.globalRoot]? .resolvingSymlinksInPath() for agent in AgentRegistry.skillAgents { - roots["skills-" + agent.rawValue] = AgentRegistry.installSkillsDirectory( - for: agent, scope: scope, environment: environment) + let key = "skills-" + agent.rawValue + roots[key] = AgentRegistry.skillRoot(key, scope: scope, environment: environment)?.directory + roots[AgentRegistry.skillRootKey(for: agent, scope: scope)] = + 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() } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 7ccb025..7a397cd 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -1187,7 +1187,8 @@ extension StateStore { } var installationResolver = SkillInstallationTargetResolver(store: self) for target in installations { - let current = try installationResolver.target(for: target.agent, named: target.name) + let current = try installationResolver.target( + for: target.agent, named: target.name, root: target.ledgerRoot) guard current.scope.path.utf8.elementsEqual(target.scope.path.utf8), current.url.path.utf8.elementsEqual(target.url.path.utf8), current.footprint == target.footprint @@ -1399,7 +1400,8 @@ extension StateStore { } var installationResolver = SkillInstallationTargetResolver(store: self) for target in context.installations { - let current = try installationResolver.target(for: target.agent, named: target.name) + let current = try installationResolver.target( + for: target.agent, named: target.name, root: target.ledgerRoot) guard current.url.path.utf8.elementsEqual(target.url.path.utf8), current.footprint == target.footprint else { throw CoreError.invalidState("installation authority changed during admission") } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 2b7b049..8eeb0fc 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -19,7 +19,10 @@ struct TransactionPaths { let canonical = installation.name.utf8.elementsEqual( PathSafety.sanitizeName(installation.name).utf8) let recorded = - canonical ? false : try persistedInstallation(installation.name, agent: installation.agent) + canonical + ? false + : try persistedInstallation( + installation.name, agent: installation.agent, root: installation.ledgerRoot) guard canonical || recorded else { throw CoreError.unsafePath("installation recipient changed") } if let route = try coordinationRoute(for: installation.path) { @@ -103,9 +106,11 @@ struct TransactionPaths { return InstructionLocations.ruleRoot(in: store.scope) + "/" + ruleName } var matchingInstallation = false - for agent in AgentRegistry.skillAgents { - let logical = AgentRegistry.installSkillsDirectory( - for: agent, scope: store.scope, environment: store.environment) + let keys = + AgentRegistry.skillAgents.map(\.rawValue) + + (store.scope == .user ? ["codex-private"] : []) + for key in keys { + guard let (agent, logical) = skillRoot(key) else { continue } let physical = logical.resolvingSymlinksInPath() let parent = destination.deletingLastPathComponent().standardizedFileURL if parent.path.utf8.elementsEqual(logical.standardizedFileURL.path.utf8) @@ -115,9 +120,10 @@ struct TransactionPaths { guard try PathSafety.sanitizeName(destination.lastPathComponent) == destination.lastPathComponent - || persistedInstallation(destination.lastPathComponent, agent: agent) + || persistedInstallation( + destination.lastPathComponent, agent: agent, root: "skills-" + key) else { continue } - let path = agent.rawValue + "/" + destination.lastPathComponent + let path = key + "/" + destination.lastPathComponent _ = try components(path) return path } @@ -190,12 +196,11 @@ struct TransactionPaths { let file = InstructionLocations.file(for: agent, scope: .user, environment: store.environment) { url = file.deletingLastPathComponent().resolvingSymlinksInPath() - } else if let agent = AgentID(rawValue: key), agent.supportsSkills { + } else if let (_, directory) = skillRoot(key) { // Configured agent containers are trusted inputs. Resolve that boundary once; // journal descendants are opened without following links and roots are identity-bound. url = try NativeRootAuthority( - loader: AgentRegistry.installSkillsDirectory( - for: agent, scope: store.scope, environment: store.environment), descendants: [] + loader: directory, descendants: [] ).physicalDirectory() } else { throw CoreError.invalidState("unknown transaction root") @@ -211,18 +216,24 @@ struct TransactionPaths { } else if key == InstructionLocations.ruleRoot(in: store.scope) { result[key] = InstructionLocations.antigravityAuthority( store.environment, scope: store.scope) - } else if let agent = AgentID(rawValue: key), agent.supportsSkills { + } else if let (_, directory) = skillRoot(key) { result[key] = NativeRootAuthority( - loader: AgentRegistry.installSkillsDirectory( - for: agent, scope: store.scope, environment: store.environment), descendants: []) + loader: directory, descendants: []) } } return result } + private func skillRoot(_ journalKey: String) -> (agent: AgentID, directory: URL)? { + AgentRegistry.skillRoot( + "skills-" + journalKey, scope: store.scope, environment: store.environment) + } + /// Only committed exact recipients authorize legacy spellings at the queue boundary. /// Recovery instead consumes the journal's already-admitted single-component path. - fileprivate func persistedInstallation(_ name: String, agent: AgentID) throws -> Bool { + fileprivate func persistedInstallation(_ name: String, agent: AgentID, root: String) throws + -> Bool + { guard agent.supportsSkills, !name.isEmpty, name != ".", name != "..", !name.contains("/"), !name.contains("\\"), !name.contains("\0"), let bytes = try store.existingData(store.resolvedURL) @@ -232,7 +243,7 @@ struct TransactionPaths { 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.kind == .registered && $0.target.root == root && $0.target.path.utf8.elementsEqual(name.utf8) && $0.recipients.contains(agent) && $0.route == "agents/skill@1" } @@ -306,7 +317,7 @@ struct TransactionPaths { throw CoreError.unsafePath("unmanaged user instruction path") } } else { - guard AgentID(rawValue: key)?.supportsSkills == true, descendants.count == 1 + guard skillRoot(key) != nil, descendants.count == 1 else { throw CoreError.unsafePath("unmanaged installation transaction path") } } return (key, descendants) @@ -346,6 +357,7 @@ package struct SkillInstallationTarget: Sendable { let path: String let scope: URL let agent: AgentID + package let ledgerRoot: String let name: String let authority: NativeRootAuthority let parentIdentity: FileObjectIdentity? @@ -379,11 +391,13 @@ package struct SkillInstallationTarget: Sendable { } extension StateStore { - package func skillInstallationTarget(for agent: AgentID, named name: String) throws + package func skillInstallationTarget( + for agent: AgentID, named name: String, root: String? = nil + ) throws -> SkillInstallationTarget { var resolver = SkillInstallationTargetResolver(store: self) - return try resolver.target(for: agent, named: name) + return try resolver.target(for: agent, named: name, root: root) } } @@ -396,7 +410,7 @@ package struct SkillInstallationTargetResolver { } private let paths: TransactionPaths - private var parents: [AgentID: Parent] = [:] + private var parents: [String: Parent] = [:] private var routes: NativeTargetRoute.UserRouteLookup package init(store: StateStore) { @@ -404,38 +418,43 @@ package struct SkillInstallationTargetResolver { routes = .init(environment: store.environment) } - private mutating func parent(for agent: AgentID) throws -> Parent { - if let known = parents[agent] { return known } - let authority = NativeRootAuthority( - loader: AgentRegistry.installSkillsDirectory( - for: agent, scope: paths.store.scope, environment: paths.store.environment), - descendants: []) + private mutating func parent(root: String, directory: URL) throws -> Parent { + if let known = parents[root] { return known } + let authority = NativeRootAuthority(loader: directory, descendants: []) let url = try authority.physicalDirectory() let ancestry = try DirectoryAccessEvidence.capture(at: url) let identity = ancestry.directories.count == url.pathComponents.count ? try DirectoryHandle(at: url).objectIdentity : nil let parent = Parent(url: url, authority: authority, identity: identity) - parents[agent] = parent + parents[root] = parent return parent } - package mutating func target(for agent: AgentID, named name: String) throws + package mutating func target(for agent: AgentID, named name: String, root: String? = nil) throws -> SkillInstallationTarget { + let root = root ?? AgentRegistry.skillRootKey(for: agent, scope: paths.store.scope) + guard + let registered = AgentRegistry.skillRoot( + root, scope: paths.store.scope, environment: paths.store.environment), + registered.agent == agent + else { throw CoreError.unsafePath("invalid installation root") } let canonical = name.utf8.elementsEqual(PathSafety.sanitizeName(name).utf8) - let recorded = canonical ? false : try paths.persistedInstallation(name, agent: agent) + let recorded = + canonical ? false : try paths.persistedInstallation(name, agent: agent, root: root) guard agent.supportsSkills, !name.isEmpty, name != ".", name != "..", !name.contains("/"), !name.contains("\\"), !name.contains("\0"), canonical || recorded else { throw CoreError.unsafePath("unrecorded installation target") } - let parent = try parent(for: agent) + let parent = try parent(root: root, directory: registered.directory) let url = parent.url.appendingPathComponent(name) - let path = agent.rawValue + "/" + name + let path = String(root.dropFirst(7)) + "/" + name let route = try paths.installationCoordinationRoute(for: agent, route: routes.route(at: url)) return SkillInstallationTarget( url: url, footprint: Set(route.map { [$0] } ?? []), path: path, scope: paths.store.directory, - agent: agent, name: name, authority: parent.authority, parentIdentity: parent.identity) + agent: agent, ledgerRoot: root, name: name, authority: parent.authority, + parentIdentity: parent.identity) } } @@ -446,7 +465,7 @@ extension TransactionPaths { 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 } + guard parts.count == 2, let (agent, _) = skillRoot(parts[0]) else { return nil } _ = try components(path) let target = try rootURL(parts[0]).appendingPathComponent(parts[1]) return try installationCoordinationRoute( diff --git a/Sources/AgentsManifest/ManifestProjection.swift b/Sources/AgentsManifest/ManifestProjection.swift index 0580230..59eda96 100644 --- a/Sources/AgentsManifest/ManifestProjection.swift +++ b/Sources/AgentsManifest/ManifestProjection.swift @@ -393,6 +393,17 @@ private struct Projection { name: name, patterns: strings(r["patterns"]), purpose: IgnorePurposeDeclaration(rawValue: r["purpose"]!.string!)!, agents: agents, condition: condition, native: native) + case "hostPlugin": + let selector: HostPluginSelector + if let id = r["pluginId"]?.string { + selector = .marketplace(pluginId: id, marketplace: r["marketplace"]?.string) + } else { + selector = .bundle(source: r["source"]!.string!, path: r["path"]!.string!) + } + return .hostPlugin( + .init( + name: name, selector: selector, agents: agents!, enabled: r["enabled"] == .boolean(true), + claudeScope: r["claudeScope"]?.string.flatMap(ClaudePluginScope.init(rawValue:)))) case "plugin": return .plugin( name: name, path: r["path"]!.string!, source: r["source"]!.string!, diff --git a/Sources/AgentsManifest/ManifestSchema.swift b/Sources/AgentsManifest/ManifestSchema.swift index ab2d9c9..6b75e9b 100644 --- a/Sources/AgentsManifest/ManifestSchema.swift +++ b/Sources/AgentsManifest/ManifestSchema.swift @@ -260,11 +260,26 @@ enum ManifestSchema { "permissions", "ignore", "plugin", ]), maximum: 10000), "exclude": .array(.named("componentReference"), maximum: 10000), ], required: ["kind", "name", "source", "path"], maximum: nil), + "component_hostPluginID": .object( + [ + "kind": .constant("hostPlugin"), "name": .string, + "agents": .array(.named("agent"), maximum: 10000), "enabled": .boolean, + "claudeScope": .enumeration(["user", "project", "local"]), "pluginId": .string, + "marketplace": .string, + ], required: ["kind", "name", "agents", "pluginId"], maximum: nil), + "component_hostPluginBundle": .object( + [ + "kind": .constant("hostPlugin"), "name": .string, + "agents": .array(.named("agent"), maximum: 10000), "enabled": .boolean, + "claudeScope": .enumeration(["user", "project", "local"]), "source": .string, + "path": .string, + ], required: ["kind", "name", "agents", "source", "path"], maximum: nil), "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"), + .named("component_plugin"), .named("component_hostPluginID"), + .named("component_hostPluginBundle"), ]), "use": .object( ["group": .string, "source": .string, "condition": .named("condition")], required: ["group"], diff --git a/Sources/AgentsManifest/Resources/agents.schema.json b/Sources/AgentsManifest/Resources/agents.schema.json index fec6bf0..7baa4b4 100644 --- a/Sources/AgentsManifest/Resources/agents.schema.json +++ b/Sources/AgentsManifest/Resources/agents.schema.json @@ -1750,6 +1750,107 @@ "additionalProperties": false, "description": "Declare a plugin resource for native installation or component expansion." }, + "component_hostPluginID": { + "type": "object", + "properties": { + "kind": { + "const": "hostPlugin", + "description": "Selects a plugin managed by an explicit host synchronization." + }, + "name": { + "type": "string", + "description": "Symbolic name of the declaration." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit recipients. A marketplace ID requires one recipient. A bundle requires at least one." + }, + "enabled": { + "type": "boolean", + "description": "Desired host enablement. Omission defaults to true." + }, + "claudeScope": { + "type": "string", + "enum": [ + "user", + "project", + "local" + ], + "description": "Claude Code scope. Omission uses the selected agents scope." + }, + "pluginId": { + "type": "string", + "description": "Host plugin ID." + }, + "marketplace": { + "type": "string", + "description": "Optional marketplace URL or path." + } + }, + "required": [ + "kind", + "name", + "agents", + "pluginId" + ], + "additionalProperties": false, + "description": "Declare a plugin for explicit host synchronization." + }, + "component_hostPluginBundle": { + "type": "object", + "properties": { + "kind": { + "const": "hostPlugin", + "description": "Selects a plugin managed by an explicit host synchronization." + }, + "name": { + "type": "string", + "description": "Symbolic name of the declaration." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit recipients. A marketplace ID requires one recipient. A bundle requires at least one." + }, + "enabled": { + "type": "boolean", + "description": "Desired host enablement. Omission defaults to true." + }, + "claudeScope": { + "type": "string", + "enum": [ + "user", + "project", + "local" + ], + "description": "Claude Code scope. Omission uses the selected agents scope." + }, + "source": { + "type": "string", + "description": "Source alias containing the plugin bundle." + }, + "path": { + "type": "string", + "description": "Relative path to one plugin directory." + } + }, + "required": [ + "kind", + "name", + "agents", + "source", + "path" + ], + "additionalProperties": false, + "description": "Declare a plugin for explicit host synchronization." + }, "component": { "oneOf": [ { @@ -1781,6 +1882,12 @@ }, { "$ref": "#/$defs/component_plugin" + }, + { + "$ref": "#/$defs/component_hostPluginID" + }, + { + "$ref": "#/$defs/component_hostPluginBundle" } ], "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." diff --git a/Sources/AgentsManifest/SourceReferenceEdits.swift b/Sources/AgentsManifest/SourceReferenceEdits.swift index 1eb3114..4a83d61 100644 --- a/Sources/AgentsManifest/SourceReferenceEdits.swift +++ b/Sources/AgentsManifest/SourceReferenceEdits.swift @@ -40,7 +40,8 @@ enum SourceReferenceEdits { case "mcpServer": child("transport") case "hook", "lspServer": child("run") case "command", "subagent": child("prompt") - case "skills", "plugin", "section", "exported", "path", "file": reference("source") + case "skills", "plugin", "hostPlugin", "section", "exported", "path", "file": + reference("source") case "executable", "stdio": reference("executableSource") child("workingDirectory") diff --git a/Sources/AgentsManifest/YAMLConstruction.swift b/Sources/AgentsManifest/YAMLConstruction.swift index 8a90327..8dc2346 100644 --- a/Sources/AgentsManifest/YAMLConstruction.swift +++ b/Sources/AgentsManifest/YAMLConstruction.swift @@ -387,6 +387,20 @@ enum YAMLConstruction { fields = [ "name": .string(name), "patterns": strings(patterns), "purpose": .string(purpose.rawValue), ] + case .hostPlugin(let value): + fields = [ + "name": .string(value.name), "agents": agents(value.agents), + "enabled": .boolean(value.enabled), "claudeScope": text(value.claudeScope?.rawValue), + ] + switch value.selector { + case .marketplace(let pluginId, let marketplace): + fields["pluginId"] = .string(pluginId) + fields["marketplace"] = text(marketplace) + case .bundle(let source, let path): + fields["source"] = .string(source) + fields["path"] = .string(path) + } + return record("hostPlugin", fields) case .plugin( let name, let path, let source, let mode, let select, let exclude, let a, let c, let n): kind = "plugin" diff --git a/Sources/AgentsManifest/YAMLDomainValidation.swift b/Sources/AgentsManifest/YAMLDomainValidation.swift index e1de657..b06a63e 100644 --- a/Sources/AgentsManifest/YAMLDomainValidation.swift +++ b/Sources/AgentsManifest/YAMLDomainValidation.swift @@ -312,6 +312,31 @@ struct YAMLDomainValidation { try resource(rule["pattern"]!.string!, pointer) } } + case "hostPlugin": + let recipients = strings(record["agents"]) + if let id = record["pluginId"]?.string { + guard recipients.count == 1 else { + throw fail(pointer + "/agents", "a marketplace plugin requires one explicit recipient") + } + guard !id.isEmpty, !id.hasPrefix("-"), + !id.contains(where: \.isWhitespace), !id.contains("\0"), !id.contains("/"), + !id.contains("\\"), id != ".", id != ".." + else { throw fail(pointer + "/pluginId", "invalid host plugin ID") } + if let marketplace = record["marketplace"]?.string { + guard !marketplace.isEmpty, !marketplace.hasPrefix("-"), !marketplace.contains("\0") + else { throw fail(pointer + "/marketplace", "invalid marketplace location") } + } + } else { + guard !recipients.isEmpty else { + throw fail(pointer + "/agents", "a plugin bundle requires explicit recipients") + } + let source = record["source"]!.string! + try alias(source, pointer + "/source") + try resource(record["path"]!.string!, pointer + "/path") + guard sources[source]?.kind != "index" else { + throw fail(pointer + "/source", "plugin bundles require a filesystem source") + } + } case "plugin": try alias(record["source"]!.string!, pointer) try resource(record["path"]!.string!, pointer) diff --git a/Sources/AgentsManifest/YAMLProjection.swift b/Sources/AgentsManifest/YAMLProjection.swift index 2e229bd..623263f 100644 --- a/Sources/AgentsManifest/YAMLProjection.swift +++ b/Sources/AgentsManifest/YAMLProjection.swift @@ -181,6 +181,9 @@ final class YAMLProjection { case "command": defaults["parameters"] = .array([]) case "lspServer": defaults["initializationOptions"] = .dictionary([:]) case "ignore": defaults["purpose"] = .string("context") + case "hostPlugin": + defaults = ["enabled": .boolean(true), "claudeScope": .null] + if input["pluginId"] != nil { defaults["marketplace"] = .null } case "plugin": defaults.merge(["mode": .string("components"), "select": .null, "exclude": .array([])]) { _, r in r diff --git a/Sources/AgentsManifest/YAMLValidation.swift b/Sources/AgentsManifest/YAMLValidation.swift index abee4be..af0c739 100644 --- a/Sources/AgentsManifest/YAMLValidation.swift +++ b/Sources/AgentsManifest/YAMLValidation.swift @@ -2,7 +2,7 @@ import AgentsCore /// The finite constraints compiled from the bundled declaration schema. No caller supplies rules. indirect enum YAMLRule: Sendable { - case string, native + case string, boolean, native case integer(minimum: Int, maximum: Int? = nil) case integerConstant(Int) case constant(String) @@ -140,12 +140,17 @@ final class YAMLValidation { } try check(pair.value, rule) } + case .boolean: + guard case .scalar(let text, let quoted, let tagged) = node.data, + !quoted, !tagged, YAMLScalar.classify(text) == .boolean + else { throw fail("expected a boolean") } case .oneOf(let choices): - // Disjoint literal discriminators permit one traversal of component/transport subtrees. - // Other unions must count all matching branches to enforce oneOf. + // Literal discriminators eliminate branches belonging to another component kind. + // Count all applicable matches to enforce oneOf. + var applicable = choices if let kind = node.pairs?.first(where: { $0.key.text == "kind" })?.value.text { - var discriminated: [String: YAMLRule] = [:] - var disjoint = true + var discriminated: [String: [YAMLRule]] = [:] + var discriminatedByKind = true for candidate in choices { let resolved: YAMLRule if case .named(let name) = candidate { @@ -156,7 +161,7 @@ final class YAMLValidation { guard case .object(let fields, let required, _) = resolved, required.contains("kind"), let discriminator = fields["kind"] else { - disjoint = false + discriminatedByKind = false break } let values: [String] @@ -164,21 +169,20 @@ final class YAMLValidation { case .constant(let value): values = [value] case .enumeration(let options): values = options default: - disjoint = false + discriminatedByKind = false values = [] } for value in values { - if discriminated.updateValue(candidate, forKey: value) != nil { disjoint = false } + discriminated[value, default: []].append(candidate) } } - if disjoint, let candidate = discriminated[kind] { - try check(node, candidate) - return + if discriminatedByKind, let matching = discriminated[kind] { + applicable = matching } } var matches = 0 var firstFailure: ManifestFailure? - for choice in choices { + for choice in applicable { do { try check(node, choice) matches += 1 diff --git a/Sources/AgentsManifest/YAMLWriter.swift b/Sources/AgentsManifest/YAMLWriter.swift index c479a71..83f20a1 100644 --- a/Sources/AgentsManifest/YAMLWriter.swift +++ b/Sources/AgentsManifest/YAMLWriter.swift @@ -101,12 +101,8 @@ enum YAMLWriter { 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) + if DeclaredComponentKind(rawValue: record.kind) != nil || ["stdio", "streamableHTTP", "sse"].contains(record.kind) { pairs.append(("kind", quote(record.kind))) @@ -117,7 +113,8 @@ enum YAMLWriter { let named = ["sources", "packages", "groups", "overrides", "chatGPT"].contains(field) let order = [ "name", "source", "url", "path", "index", "requirement", "subpath", "select", "exclude", - "mode", "overrides", "sections", "chatGPT", "description", "prompt", "model", "tools", + "mode", "pluginId", "marketplace", "enabled", "claudeScope", "overrides", "sections", + "chatGPT", "description", "prompt", "model", "tools", "parameters", "transport", "event", "run", "matcher", "timeoutSeconds", "executable", "executableSource", "arguments", "environment", "workingDirectory", "headers", "languages", "initializationOptions", "rules", "operation", "pattern", "patterns", "purpose", diff --git a/Sources/AgentsSkills/Discovery.swift b/Sources/AgentsSkills/Discovery.swift index e279e35..1c4f2ec 100644 --- a/Sources/AgentsSkills/Discovery.swift +++ b/Sources/AgentsSkills/Discovery.swift @@ -98,7 +98,7 @@ enum Discovery { ) throws -> [Skill] { let searchRoot = try subpath.map { try PathSafety.resolvedChild(base: base, subpath: $0) } ?? base - let pluginGroups = try pluginGroupings(base: searchRoot) + let plugins = try pluginSkills(base: searchRoot) let projectInstalledSkillNames = projectInstalledAgentSkillNames(base: searchRoot) var skills: [Skill] = [] var seen = Set() @@ -131,7 +131,7 @@ enum Discovery { { return false } - skill.pluginName = pluginGroups[directory.standardizedFileURL.path] + skill.pluginName = plugins.groups[directory.standardizedFileURL.path] skills.append(skill) seen.insert(key) return true @@ -153,7 +153,7 @@ enum Discovery { searchRoot.appendingPathComponent(".codex/skills"), searchRoot.appendingPathComponent(".opencode/skills"), ] - priorityDirectories.append(contentsOf: try pluginSkillSearchDirectories(base: searchRoot)) + priorityDirectories.append(contentsOf: plugins.directories) for directory in priorityDirectories { let candidates = @@ -301,94 +301,53 @@ enum Discovery { (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true } - private static func pluginSkillSearchDirectories(base: URL) throws -> [URL] { + private static func pluginSkills(base: URL) throws + -> (directories: [URL], groups: [String: String]) + { var directories: [URL] = [] + var groups: [String: String] = [:] let decoder = JSONDecoder() - let marketplaceURL = base.appendingPathComponent(".claude-plugin/marketplace.json") - if let data = try FileSystem.readUnlessDenied(at: marketplaceURL), - let manifest = try? decoder.decode(MarketplaceManifest.self, from: data) - { - let root = manifest.metadata?.pluginRoot - if root == nil || root?.hasPrefix("./") == true { - for plugin in manifest.plugins ?? [] { - guard plugin.sourceObject == nil else { continue } - guard isAllowedMarketplaceSource(plugin.source, pluginRoot: root) else { continue } - let pluginBase = base.appendingPathComponent(root ?? ".").appendingPathComponent( - plugin.source ?? "." - ).standardizedFileURL - guard PathSafety.isContained(pluginBase, in: base) else { continue } - for skill in plugin.skills ?? [] where skill.hasPrefix("./") { - let parent = pluginBase.appendingPathComponent(skill).deletingLastPathComponent() - .standardizedFileURL - if PathSafety.isContained(parent, in: base) { - directories.append(parent) - } - } - directories.append(pluginBase.appendingPathComponent("skills")) - } - } - } - - let pluginURL = base.appendingPathComponent(".claude-plugin/plugin.json") - 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("./") { - let parent = base.appendingPathComponent(skill).deletingLastPathComponent() - .standardizedFileURL - if PathSafety.isContained(parent, in: base) { - directories.append(parent) - } + func add(_ root: URL, name: String?, skills: [String], prefer: Bool = false) { + for path in skills where path.hasPrefix("./") { + let skill = root.appendingPathComponent(path).standardizedFileURL + guard PathSafety.isContained(skill, in: base) else { continue } + directories.append(skill.deletingLastPathComponent()) + if let name, prefer || groups[skill.path] == nil { groups[skill.path] = name } } - directories.append(base.appendingPathComponent("skills")) + directories.append(root.appendingPathComponent("skills")) } - return directories - } - - 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 FileSystem.readUnlessDenied(at: marketplaceURL), - let manifest = try? decoder.decode(MarketplaceManifest.self, from: data) - { + for path in [".claude-plugin/marketplace.json", ".agents/plugins/marketplace.json"] { + let file = base.appendingPathComponent(path) + guard let data = try FileSystem.readUnlessDenied(at: file), + let manifest = try? decoder.decode(MarketplaceManifest.self, from: data) + else { continue } let root = manifest.metadata?.pluginRoot - if root == nil || root?.hasPrefix("./") == true { - for plugin in manifest.plugins ?? [] { - guard let name = plugin.name else { continue } - guard plugin.sourceObject == nil else { continue } - guard isAllowedMarketplaceSource(plugin.source, pluginRoot: root) else { continue } - let pluginBase = base.appendingPathComponent(root ?? ".").appendingPathComponent( - plugin.source ?? "." - ).standardizedFileURL - guard PathSafety.isContained(pluginBase, in: base) else { continue } - for skill in plugin.skills ?? [] where skill.hasPrefix("./") { - let skillDir = pluginBase.appendingPathComponent(skill).standardizedFileURL - if PathSafety.isContained(skillDir, in: base) { - groups[skillDir.path] = name - } - } - } + guard root == nil || root?.hasPrefix("./") == true else { continue } + for plugin in manifest.plugins ?? [] { + let local = + path == ".agents/plugins/marketplace.json" ? plugin.sourceObject?.localPath : nil + guard plugin.sourceObject == nil || local != nil else { continue } + let source = plugin.source ?? local + guard isAllowedMarketplaceSource(source, pluginRoot: root) else { continue } + let directory = base.appendingPathComponent(root ?? ".") + .appendingPathComponent(source ?? ".").standardizedFileURL + guard PathSafety.isContained(directory, in: base) else { continue } + add(directory, name: plugin.name, skills: plugin.skills ?? []) } } - let pluginURL = base.appendingPathComponent(".claude-plugin/plugin.json") - if let data = try FileSystem.readUnlessDenied(at: pluginURL), - let manifest = try? decoder.decode(PluginManifest.self, from: data), - let name = manifest.name - { - for skill in manifest.skills ?? [] where skill.hasPrefix("./") { - let skillDir = base.appendingPathComponent(skill).standardizedFileURL - if PathSafety.isContained(skillDir, in: base) { - groups[skillDir.path] = name - } - } + for path in [".claude-plugin/plugin.json", "plugin.json"] { + let file = base.appendingPathComponent(path) + guard let data = try FileSystem.readUnlessDenied(at: file), + let manifest = try? decoder.decode(PluginManifest.self, from: data), + path != "plugin.json" || manifest.schema == AgentPluginManifest.schema + else { continue } + add(base, name: manifest.name, skills: manifest.skills ?? [], prefer: path != "plugin.json") } - return groups + return (directories, groups) } private static func isAllowedMarketplaceSource(_ source: String?, pluginRoot: String?) -> Bool { @@ -445,10 +404,19 @@ private struct PluginEntry: Decodable { struct SourceObject: Decodable { var source: String? var repo: String? + var path: String? + + var localPath: String? { source == "local" ? path : nil } } } private struct PluginManifest: Decodable { + var schema: String? + enum CodingKeys: String, CodingKey { + case schema = "$schema" + case skills, name + } + var skills: [String]? var name: String? } diff --git a/Sources/AgentsSkills/GovernanceDiscovery.swift b/Sources/AgentsSkills/GovernanceDiscovery.swift new file mode 100644 index 0000000..488732d --- /dev/null +++ b/Sources/AgentsSkills/GovernanceDiscovery.swift @@ -0,0 +1,35 @@ +import Foundation + +extension SkillOperations { + /// Reads skill metadata under an explicitly selected host loader directory. + package static func governanceSkills( + in root: URL, includeInternal: Bool + ) throws -> [Skill] { + let children: [URL] + do { + children = try FileManager.default.contentsOfDirectory( + at: root.resolvingSymlinksInPath(), includingPropertiesForKeys: nil, + options: [.skipsHiddenFiles]) + } catch let error as CocoaError + where [.fileNoSuchFile, .fileReadNoSuchFile].contains(error.code) + { + return [] + } + let ordered = children.sorted { + $0.lastPathComponent.utf8.lexicographicallyPrecedes($1.lastPathComponent.utf8) + } + return try ordered.compactMap { url in + try parseGovernanceSkill( + at: root.appendingPathComponent(url.lastPathComponent), includeInternal: includeInternal) + } + } + + package static func parseGovernanceSkill(at root: URL, includeInternal: Bool) throws -> Skill? { + let skill = root.appendingPathComponent("SKILL.md") + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: skill.path, isDirectory: &isDirectory), + !isDirectory.boolValue + else { return nil } + return try Discovery.parseSkill(at: skill, includeInternal: includeInternal) + } +} diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index b49090c..fc469b5 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -111,10 +111,12 @@ package final class SkillLifecycle { 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 + let root = deployment.target.root, + AgentRegistry.skillRoot(root, scope: store.scope, environment: store.environment)?.agent + == agent else { throw CoreError.invalidState("invalid skill installation recipient") } let name = deployment.target.path - targets[agent.rawValue + "/" + name] = try resolver.target(for: agent, named: name) + targets[root + "/" + name] = try resolver.target(for: agent, named: name, root: root) } return targets } diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginCommandRunner.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginCommandRunner.swift new file mode 100644 index 0000000..b66fbb2 --- /dev/null +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginCommandRunner.swift @@ -0,0 +1,85 @@ +import AgentsCore +import Foundation + +/// Vendor commands receive no interactive input. Captured output is used only to classify failures. +public struct ProcessHostPluginCommandRunner: HostPluginCommandRunner { + public let timeout: Duration + + public init(timeout: Duration = .seconds(120)) { + self.timeout = timeout + } + + public func run(argv: [String], environment: RuntimeEnvironment) async -> HostPluginCommandResult + { + guard let executable = argv.first, timeout > .zero, !Task.isCancelled else { return .failed } + let deadline = ContinuousClock.now + timeout + var variables = environment.environment + variables["HOME"] = environment.homeDirectory.path + variables["GIT_TERMINAL_PROMPT"] = "0" + variables["GCM_INTERACTIVE"] = "never" + guard let path = variables["PATH"], + path.split(separator: ":", omittingEmptySubsequences: false) + .contains(where: { entry in + let base = URL( + fileURLWithPath: String(entry), + relativeTo: URL( + fileURLWithPath: environment.projectDirectory.path, isDirectory: true)) + let path = base.appendingPathComponent(executable).path + var directory: ObjCBool = false + return FileManager.default.fileExists(atPath: path, isDirectory: &directory) + && !directory.boolValue && FileManager.default.isExecutableFile(atPath: path) + }) + else { return .cliUnavailable } + let process: OwnedDuplexProcess + do { + process = try OwnedDuplexProcess( + .init( + executable: executable, arguments: Array(argv.dropFirst()), + directory: environment.projectDirectory, environment: variables)) + } catch { return .failed } + process.closeInput() + + var output = Data() + var errors = Data() + func read(_ stream: () throws -> DuplexRead, into bytes: inout Data, limit: Int = 16) throws { + for _ in 0.. 32_768 { bytes.removeFirst(bytes.count - 32_768) } + } + } + + var result: HostPluginCommandResult = .timeout + do { + while true { + try Task.checkCancellation() + try read(process.readStandardOutput, into: &output) + try read(process.readStandardError, into: &errors) + if let exit = process.exitIfFinished() { + try read(process.readStandardOutput, into: &output, limit: 1_024) + try read(process.readStandardError, into: &errors, limit: 1_024) + if case .status(0) = exit { + result = .success + } else { + let message = String(decoding: errors + output, as: UTF8.self).lowercased() + let auth = [ + "authentication required", "not logged in", "not authenticated", "please log in", + "please login", "sign in to", "login required", "unauthorized", "status 401", + "authentication failed", "authentication_required", "auth_required", + ] + result = auth.contains(where: message.contains) ? .authRequired : .failed + } + break + } + if ContinuousClock.now >= deadline { break } + try await Task.sleep(for: .milliseconds(10)) + } + } catch { result = .failed } + guard + await process.finish( + grace: .zero, terminate: .milliseconds(100), killWait: .seconds(2)) + else { return result == .timeout ? .timeout : .failed } + return result + } +} diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginDocuments.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginDocuments.swift new file mode 100644 index 0000000..9e013bc --- /dev/null +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginDocuments.swift @@ -0,0 +1,89 @@ +import AgentsCore +import Foundation +import NativeDocuments + +enum HostPluginDocuments { + static let maximumBytes = 8 * 1024 * 1024 + + static func read(_ url: URL, format: NativeDocumentFormat = .json) throws -> NativeDocument? { + let file = try TargetPrecondition.readingFile(url, maximumFileBytes: maximumBytes) + return try file.bytes.map { try parse($0, format: format) } + } + + static func parse(_ bytes: Data, format: NativeDocumentFormat) throws -> NativeDocument { + try NativeDocument( + bytes: bytes, format: format, + budget: .init( + limits: .init( + storage: maximumBytes * 16, work: maximumBytes * 32, nodes: 200_000, depth: 64, + uninterruptedBytes: maximumBytes))) + } + + static func directory(_ url: URL) throws -> [URL] { + do { + return try FileManager.default.contentsOfDirectory( + at: url, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles] + ).sorted { $0.lastPathComponent.utf8.lexicographicallyPrecedes($1.lastPathComponent.utf8) } + } catch let error as CocoaError + where [.fileNoSuchFile, .fileReadNoSuchFile].contains(error.code) + { + return [] + } + } + + static func boolean(_ value: NativeValue?) throws -> Bool? { + guard let value else { return nil } + guard case .boolean(let result) = value else { + throw CoreError.invalidState("host plugin enablement has an invalid value") + } + return result + } + + static func safeID(_ value: String) -> Bool { + !value.isEmpty && !value.hasPrefix("-") && value != "." && value != ".." + && !value.contains(where: { $0.isWhitespace || $0.isNewline }) + && !value.contains("/") && !value.contains("\\") && !value.contains("\0") + } + + static func fields(_ value: NativeValue?) throws -> [String: NativeValue] { + guard let value else { return [:] } + guard case .object(let fields) = value else { + throw CoreError.invalidState("host plugin document has an invalid object") + } + return fields + } + + static func list(_ value: NativeValue?) throws -> [NativeValue] { + guard let value else { return [] } + guard case .array(let list) = value else { + throw CoreError.invalidState("host plugin document has an invalid array") + } + return list + } + + static func strings(_ value: NativeValue?) throws -> [String] { + try list(value).map { value in + guard let text = value.hostString else { + throw CoreError.invalidState("host plugin document has an invalid string array") + } + return text + } + } +} + +extension NativeValue { + var hostString: String? { + if case .string(let value) = self { return value } + return nil + } +} + +extension NativeDocument { + func hostValue(_ keys: [String]) throws -> NativeValue? { + guard let observation = try read(.init(keys: keys)) else { return nil } + guard let value = observation.value else { + throw CoreError.invalidState("host plugin document could not be projected") + } + return value + } +} diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift new file mode 100644 index 0000000..5eb6a60 --- /dev/null +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift @@ -0,0 +1,359 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Read-only host inventory and explicit, independently reconciled plugin synchronization. +public enum HostPluginExecutor { + public static func inspect( + scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = .init(), includeUnmanaged: Bool = true + ) throws -> [HostPluginStatus] { + let targets = try HostPluginTarget.load(scope: scope, agents: agents, environment: environment) + let locations = HostPluginLocations(environment: environment) + var result = targets.map { plan($0, locations: locations).preview.status } + if includeUnmanaged { + for agent in AgentID.allCases + where HostPluginTarget.supportedAgents.contains(agent) && (agents?.contains(agent) ?? true) { + let known = Set(targets.filter { $0.agent == agent }.compactMap(\.id)) + do { + let inventory = try locations.inventory(agent: agent, scope: scope) + result += inventory.plugins.values.filter { !known.contains($0.id) }.map { + .init( + agent: agent, scope: scope, claudeScope: nil, name: $0.name, pluginId: $0.id, + desiredEnabled: nil, installed: $0.installed, explicitEnabled: $0.explicit, + effectiveEnabled: $0.effective, locations: $0.locations, + drift: $0.installed == nil ? .unverified : .current, diagnostic: nil) + } + } catch where targets.contains(where: { $0.agent == agent }) { + // The declared entries already report the same unreadable host inventory. + } catch { + result.append( + .init( + agent: agent, scope: scope, claudeScope: nil, name: agent.displayName, pluginId: nil, + desiredEnabled: nil, installed: nil, explicitEnabled: nil, effectiveEnabled: nil, + locations: [], drift: .unverified, + diagnostic: "Host plugin inventory could not be read.")) + } + } + } + return result.sorted { + ($0.agent.rawValue, $0.name, $0.pluginId ?? "", $0.claudeScope?.rawValue ?? "") + < ($1.agent.rawValue, $1.name, $1.pluginId ?? "", $1.claudeScope?.rawValue ?? "") + } + } + + public static func preview( + scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = .init() + ) throws -> [HostPluginPreview] { + let locations = HostPluginLocations(environment: environment) + return try HostPluginTarget.load(scope: scope, agents: agents, environment: environment) + .map { plan($0, locations: locations).preview } + } + + public static func sync( + scope: InstallScope = .project, agents: [AgentID]? = nil, apply: Bool = false, + environment: RuntimeEnvironment = .init(), + runner: any HostPluginCommandRunner = ProcessHostPluginCommandRunner() + ) async throws -> [HostPluginSyncResult] { + let targets = try HostPluginTarget.load(scope: scope, agents: agents, environment: environment) + let locations = HostPluginLocations(environment: environment) + if !apply { + return targets.map { + let preview = plan($0, locations: locations).preview + return .init( + preview: preview, status: preview.status, outcome: nil, commandsRun: [], diagnostic: nil) + } + } + + var result: [HostPluginSyncResult] = [] + for target in targets { + try Task.checkCancellation() + result.append(await applyTarget(target, locations: locations, runner: runner)) + } + return result + } + + private enum CommandRole { + case marketplace, validate, install, toggle + } + + private struct Command { + let role: CommandRole + let argv: [String] + } + + private struct Plan { + let preview: HostPluginPreview + let commands: [Command] + let edits: [HostPluginConfigurationChange] + } + + private static func plan( + _ target: HostPluginTarget, locations: HostPluginLocations + ) -> Plan { + let enabled = target.declaration.enabled + var observed: ObservedHostPlugin? + func report( + _ drift: HostPluginDrift, _ reason: String? = nil, commands: [Command] = [], + changes: [HostPluginConfigurationChange] = [], edits: [HostPluginConfigurationChange] = [] + ) -> Plan { + let status = HostPluginStatus( + agent: target.agent, scope: target.scope, claudeScope: target.claudeScope, + name: target.declaration.name, pluginId: target.id, desiredEnabled: enabled, + installed: observed?.installed, explicitEnabled: observed?.explicit, + effectiveEnabled: observed?.effective, locations: observed?.locations ?? [], + drift: drift, diagnostic: reason) + return .init( + preview: .init( + status: status, commands: commands.map(\.argv), configurationChanges: changes), + commands: commands, edits: edits) + } + if let issue = target.issue { return report(issue.0, issue.1) } + guard let id = target.id else { return report(.unverified, "Host plugin ID is unavailable.") } + + do { + let inventory = try locations.inventory( + agent: target.agent, scope: target.scope, claudeScope: target.claudeScope) + observed = inventory.plugins[id] ?? .init(id: id, name: id, installed: false) + if target.agent == .antigravity, target.scope == .project, target.bundle != nil, + observed?.projectRegistered != true + { + observed?.installed = false + } + + if target.agent == .antigravity, enabled { + if target.scope == .project, observed?.globalDisabled == true { + return report( + .unsupported, "Project scope cannot re-enable a globally disabled Antigravity plugin.") + } + if observed?.manifestDisabled == true { + return report(.unsupported, "The Antigravity plugin manifest disables the plugin.") + } + } + + let missing = observed?.installed != true + let toggle = + observed?.effective != enabled || observed?.explicit.map { $0 != enabled } == true + if !missing && !toggle { return report(.current) } + var commands: [Command] = [] + var changes: [HostPluginConfigurationChange] = [] + var edits: [HostPluginConfigurationChange] = [] + func command(_ role: CommandRole, _ argv: [String]) { + commands.append(.init(role: role, argv: argv)) + } + func change( + _ file: URL, key: [String], before: HostPluginConfigurationValue?, + after: HostPluginConfigurationValue, + direct: Bool = false + ) { + let value = HostPluginConfigurationChange( + file: file, key: key, before: before, after: after) + changes.append(value) + if direct { edits.append(value) } + } + + switch target.agent { + case .codex: + if missing { + if let source = target.marketplaceSource, let catalog = target.marketplaceName, + !inventory.marketplaces.contains(catalog) + { + command(.marketplace, ["codex", "plugin", "marketplace", "add", source]) + } + command(.install, ["codex", "plugin", "add", id, "--json"]) + } + if toggle { + change( + locations.codexConfig(target.scope), key: ["plugins", id, "enabled"], + before: observed?.explicit.map(HostPluginConfigurationValue.boolean), + after: .boolean(enabled), + direct: true) + } + case .claudeCode: + let scope = target.claudeScope! + let args = ["--scope", scope.rawValue] + if missing { + if let source = target.marketplaceSource, let catalog = target.marketplaceName, + !inventory.marketplaces.contains(catalog) + { + command(.marketplace, ["claude", "plugin", "marketplace", "add", source]) + } + command(.install, ["claude", "plugin", "install", id] + args) + } + if toggle { + command(.toggle, ["claude", "plugin", enabled ? "enable" : "disable", id] + args) + change( + locations.claudeSettings(scope), key: ["enabledPlugins", id], + before: observed?.explicit.map(HostPluginConfigurationValue.boolean), + after: .boolean(enabled)) + } + case .antigravity where target.scope == .user: + if missing { + let selector: String + if let bundle = target.bundle { + command(.validate, ["agy", "plugin", "validate", bundle.path]) + selector = bundle.path + } else if case .marketplace(let raw, _) = target.declaration.selector { + selector = raw + } else { + return report( + .unsupported, "Antigravity requires a readable plugin directory or marketplace ID.") + } + command(.install, ["agy", "plugin", "install", selector]) + } + if toggle { + command(.toggle, ["agy", "plugin", enabled ? "enable" : "disable", id]) + change( + locations.antigravityUser.appendingPathComponent("config.json"), + key: ["plugins", id, "enabled"], + before: observed?.explicit.map(HostPluginConfigurationValue.boolean), + after: .boolean(enabled)) + } + case .antigravity: + if missing { + guard let bundle = target.bundle else { + return report( + .unsupported, + "A project Antigravity plugin needs a local bundle or an existing installation.") + } + let root = locations.project.path + let path = + PathSafety.isContained(bundle, in: locations.project) + ? PathSafety.relativePath(bundle.path, to: root) : bundle.path + change( + locations.antigravityProject, key: ["entries"], before: nil, after: .appendPath(path), + direct: true) + } + let prior = inventory.exclusions + var next = prior.filter { $0 != id } + if !enabled { next.append(id) } + if next != prior { + change( + locations.antigravityProject, key: ["exclude"], before: .strings(prior), + after: .strings(next), direct: true) + } + default: + return report(.unsupported, "This agent has no host plugin sync adapter.") + } + let drift: HostPluginDrift = + missing + ? (observed?.installed == nil ? .unverified : .missing) : .enablement + return report(drift, commands: commands, changes: changes, edits: edits) + } catch { + return report(.unverified, "Host plugin inventory could not be read.") + } + } + + private static func applyTarget( + _ target: HostPluginTarget, locations: HostPluginLocations, runner: any HostPluginCommandRunner + ) async -> HostPluginSyncResult { + let initial = plan(target, locations: locations) + var current = initial + var ran: [[String]] = [] + var edited = false + var installed = false + func finish(_ outcome: HostPluginOutcome, _ diagnostic: String? = nil) -> HostPluginSyncResult { + .init( + preview: initial.preview, status: current.preview.status, outcome: outcome, + commandsRun: ran, diagnostic: diagnostic ?? current.preview.status.diagnostic) + } + + while !Task.isCancelled { + let status = current.preview.status + if status.drift == .unsupported { return finish(.unsupported) } + if let command = current.commands.first(where: { + $0.role != .validate || !ran.contains($0.argv) + }) { + guard !ran.contains(command.argv) else { + return finish(.failed, "Host readback did not confirm the completed command.") + } + ran.append(command.argv) + let result = await runner.run(argv: command.argv, environment: locations.environment) + current = plan(target, locations: locations) + switch result { + case .success: + if command.role == .install, current.preview.status.installed == true { installed = true } + continue + case .cliUnavailable: return finish(.cliUnavailable) + case .authRequired: return finish(.authRequired) + case .timeout: return finish(.timeout) + case .failed: return finish(.failed) + } + } + + if !current.edits.isEmpty { + guard !edited else { + return finish(.failed, "Host readback did not confirm the settings edit.") + } + edited = true + do { + try edit(target: target, changes: current.edits, environment: locations.environment) + current = plan(target, locations: locations) + if initial.preview.status.installed != true, current.preview.status.installed == true { + installed = true + } + continue + } catch { + current = plan(target, locations: locations) + return finish(.failed, "Host plugin settings could not be edited.") + } + } + guard status.drift == .current else { + return finish(.failed, "Host readback could not verify the declared plugin state.") + } + if installed { return finish(.installed) } + if edited || !ran.isEmpty { return finish(target.declaration.enabled ? .enabled : .disabled) } + return finish(.unchanged) + } + return finish(.failed, "Host plugin synchronization was cancelled.") + } + + private static func edit( + target: HostPluginTarget, changes: [HostPluginConfigurationChange], + environment: RuntimeEnvironment + ) throws { + let store = StateStore(scope: target.scope, environment: environment) + let codex = target.agent == .codex + let route: HostPluginConfigurationRoute = codex ? .codex : .antigravityProject + try route.edit(store: store, maximumFileBytes: HostPluginDocuments.maximumBytes) { bytes in + let document = try HostPluginDocuments.parse( + bytes ?? Data((codex ? "" : "{}\n").utf8), format: codex ? .toml : .json) + var edits: [NativeRegionEdit] = [] + for change in changes { + let region = NativeRegion(keys: change.key) + let existing = try document.read(region) + let expected = existing.map(NativeExpectedRegion.owned) ?? .absent + switch change.after { + case .boolean(let desired): + _ = try HostPluginDocuments.boolean(existing?.value) + edits.append(.put(region: region, expected: expected, value: .boolean(desired))) + case .appendPath(let path): + let entries = try HostPluginDocuments.list(existing?.value) + guard + try !entries.contains(where: { + try HostPluginDocuments.fields($0)["path"]?.hostString == path + }) + else { continue } + let entry = NativeValue.object(["path": .string(path)]) + if existing == nil { + edits.append(.put(region: region, expected: .absent, value: .array([entry]))) + } else { + edits.append(.append(region: region, expected: expected, value: entry)) + } + case .strings: + let id = target.id! + let before = try HostPluginDocuments.strings(existing?.value) + var after = before.filter { $0 != id } + if !target.declaration.enabled { after.append(id) } + if before != after { + edits.append( + .put( + region: region, expected: expected, value: .array(after.map(NativeValue.string)))) + } + } + } + return try edits.isEmpty ? nil : document.prepare(edits).bytes + } + } +} diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift new file mode 100644 index 0000000..e53f122 --- /dev/null +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift @@ -0,0 +1,336 @@ +import AgentsCore +import Foundation +import NativeDocuments + +struct ObservedHostPlugin { + let id: String + var name: String + var installed: Bool? + var explicit: Bool? + var effective: Bool? + var locations: [URL] = [] + var globalDisabled = false + var projectRegistered = false + var manifestDisabled = false +} + +struct HostPluginInventory { + var plugins: [String: ObservedHostPlugin] = [:] + var marketplaces: Set = [] + var exclusions: [String] = [] +} + +struct HostPluginLocations { + let environment: RuntimeEnvironment + var project: URL { environment.projectDirectory } + var codexUser: URL { + AgentRegistry.userSkillsDirectory(for: .codex, environment: environment) + .deletingLastPathComponent() + } + var claudeUser: URL { + AgentRegistry.userSkillsDirectory(for: .claudeCode, environment: environment) + .deletingLastPathComponent() + } + var antigravityUser: URL { environment.homeDirectory.appendingPathComponent(".gemini/config") } + var antigravityProject: URL { project.appendingPathComponent(".agents/plugins.json") } + + func codexConfig(_ scope: InstallScope) -> URL { + (scope == .user ? codexUser : project.appendingPathComponent(".codex")) + .appendingPathComponent("config.toml") + } + + func claudeSettings(_ scope: ClaudePluginScope) -> URL { + switch scope { + case .user: claudeUser.appendingPathComponent("settings.json") + case .project: project.appendingPathComponent(".claude/settings.json") + case .local: project.appendingPathComponent(".claude/settings.local.json") + } + } + + func inventory(agent: AgentID, scope: InstallScope, claudeScope: ClaudePluginScope? = nil) + throws -> HostPluginInventory + { + switch agent { + case .codex: return try codex(scope) + case .claudeCode: + return try claude(claudeScope ?? (scope == .user ? .user : .project), scope: scope) + case .antigravity: return try antigravity(scope) + default: return .init() + } + } + + private func codex(_ scope: InstallScope) throws -> HostPluginInventory { + let user = try HostPluginDocuments.read(codexConfig(.user), format: .toml) + let local = + scope == .project + ? try HostPluginDocuments.read(codexConfig(.project), format: .toml) : nil + let globalEntries = try HostPluginDocuments.fields(user?.hostValue(["plugins"])) + let localEntries = try HostPluginDocuments.fields(local?.hostValue(["plugins"])) + let marketplaceEntries = try HostPluginDocuments.fields(user?.hostValue(["marketplaces"])) + var cache: [String: URL] = [:] + let cacheRoot = codexUser.appendingPathComponent("plugins/cache") + for marketplace in try HostPluginDocuments.directory(cacheRoot) + where Self.isDirectory(marketplace) { + for plugin in try HostPluginDocuments.directory(marketplace) where Self.isDirectory(plugin) { + let versions = try HostPluginDocuments.directory(plugin).sorted { + $0.lastPathComponent.compare($1.lastPathComponent, options: [.numeric, .literal]) + == .orderedDescending + } + if let bundle = try versions.first(where: { try Self.isDirectory($0) && isCodexBundle($0) }) + { + cache[plugin.lastPathComponent + "@" + marketplace.lastPathComponent] = bundle + } + } + } + var catalogBundles: [String: URL] = [:] + if scope == .project, + let catalog = try HostMarketplace.read( + at: project, manifest: ".agents/plugins/marketplace.json") + { + for id in localEntries.keys { + if let bundle = try catalog.localBundle(for: id) { catalogBundles[id] = bundle } + } + } + var result = HostPluginInventory(marketplaces: Set(marketplaceEntries.keys)) + for id in Set(cache.keys).union(globalEntries.keys).union(localEntries.keys).sorted() { + let global = try HostPluginDocuments.fields(globalEntries[id]) + let project = try HostPluginDocuments.fields(localEntries[id]) + let globalToggle = try HostPluginDocuments.boolean(global["enabled"]) + let projectToggle = try HostPluginDocuments.boolean(project["enabled"]) + let bundle = catalogBundles[id] ?? cache[id] + let configured = globalEntries[id] != nil || localEntries[id] != nil + let installed: Bool? = bundle == nil ? (configured ? nil : false) : (configured ? true : nil) + result.plugins[id] = .init( + id: id, name: String(id.split(separator: "@").first ?? Substring(id)), + installed: installed, explicit: scope == .user ? globalToggle : projectToggle, + effective: installed == true ? (projectToggle ?? globalToggle ?? true) : nil, + locations: bundle.map { [$0] } ?? []) + } + return result + } + + private func isCodexBundle(_ url: URL) throws -> Bool { + // Cache contents can be valid host bundles without a portable manifest. + for manifest in [".codex-plugin/plugin.json", "plugin.json"] { + if try HostPluginDocuments.read(url.appendingPathComponent(manifest)) != nil { return true } + } + return false + } + + private func claude(_ selection: ClaudePluginScope, scope: InstallScope) throws + -> HostPluginInventory + { + let registry = try HostPluginDocuments.read( + claudeUser.appendingPathComponent("plugins/installed_plugins.json")) + let entries = try HostPluginDocuments.fields(registry?.hostValue(["plugins"])) + let scopes: [ClaudePluginScope] = + scope == .user && selection == .user + ? [.user] : [.user, .project, .local] + var settings: [ClaudePluginScope: [String: NativeValue]] = [:] + for level in scopes { + let document = try HostPluginDocuments.read( + claudeSettings(level), format: .jsonc(trailingCommas: true)) + settings[level] = try HostPluginDocuments.fields(document?.hostValue(["enabledPlugins"])) + } + let market = try HostPluginDocuments.read( + claudeUser.appendingPathComponent("plugins/known_marketplaces.json")) + var result = HostPluginInventory( + marketplaces: Set( + try HostPluginDocuments.fields(market?.hostValue([])).keys)) + let ids = settings.values.reduce(into: Set(entries.keys)) { $0.formUnion($1.keys) } + for id in ids.sorted() { + let installations = try HostPluginDocuments.list(entries[id]).map { + try HostPluginDocuments.fields($0) + }.compactMap { entry -> (ClaudePluginScope, URL?)? in + guard let name = entry["scope"]?.hostString, let level = ClaudePluginScope(rawValue: name), + scopes.contains(level) + else { return nil } + if level != .user, let root = entry["projectPath"]?.hostString, + URL(fileURLWithPath: root).resolvingSymlinksInPath().path + != project.resolvingSymlinksInPath().path + { + return nil + } + let path = entry["installPath"]?.hostString + let url = path.flatMap { $0.hasPrefix("/") ? URL(fileURLWithPath: $0) : nil } + return (level, url) + } + let selected = installations.filter { $0.0 == selection } + let locations = scopes.reversed().flatMap { level in + installations.filter { $0.0 == level }.compactMap(\.1).sorted { $0.path < $1.path } + }.filter(Self.isDirectory) + let explicit = try HostPluginDocuments.boolean(settings[selection]?[id]) + let effective = try scopes.reversed().lazy.compactMap { + try HostPluginDocuments.boolean(settings[$0]?[id]) + }.first + let installed = + selected.isEmpty ? false : selected.contains { $0.1.map(Self.isDirectory) == true } + result.plugins[id] = .init( + id: id, name: String(id.split(separator: "@").first ?? Substring(id)), + installed: installed, explicit: explicit, + effective: locations.isEmpty ? nil : (effective ?? true), locations: locations) + } + return result + } + + private func antigravity(_ scope: InstallScope) throws -> HostPluginInventory { + let config = try HostPluginDocuments.read(antigravityUser.appendingPathComponent("config.json")) + let settings = try HostPluginDocuments.fields(config?.hostValue(["plugins"])) + let user = try antigravityBundles(at: antigravityUser.appendingPathComponent("plugins")) + var project: [String: (name: String, url: URL, disabled: Bool)] = [:] + var exclusions: [String] = [] + if scope == .project { + let manifest = try HostPluginDocuments.read(antigravityProject) + exclusions = try HostPluginDocuments.strings(manifest?.hostValue(["exclude"])) + project = try antigravityBundles(at: self.project.appendingPathComponent(".agents/plugins")) + var visited = Set() + for (id, bundle) in try antigravityEntries( + in: antigravityProject, base: self.project, depth: 0, visited: &visited) + where project[id] == nil { + project[id] = bundle + } + } + var result = HostPluginInventory(exclusions: exclusions) + for id in Set(user.keys).union(project.keys).union(settings.keys).sorted() { + let global = user[id] + let local = project[id] + let entry = try HostPluginDocuments.fields(settings[id]) + let toggle = try HostPluginDocuments.boolean(entry["enabled"]) + let excluded = exclusions.contains(id) + let bundle = local ?? global + let disabled = bundle?.disabled == true + result.plugins[id] = .init( + id: id, name: bundle?.name ?? id, installed: bundle != nil, + explicit: scope == .user ? toggle : (excluded ? false : nil), + effective: bundle == nil ? nil : !excluded && !disabled && toggle != false, + locations: bundle.map { [$0.url] } ?? [], + globalDisabled: global?.disabled == true || toggle == false, + projectRegistered: local != nil, + manifestDisabled: disabled) + } + return result + } + + private static func isDirectory(_ url: URL) -> Bool { + var directory: ObjCBool = false + return FileManager.default.fileExists(atPath: url.path, isDirectory: &directory) + && directory.boolValue + } + + private typealias AntigravityBundle = (name: String, url: URL, disabled: Bool) + + private func antigravityBundles(at root: URL) throws -> [String: AntigravityBundle] { + var result: [String: AntigravityBundle] = [:] + for url in try HostPluginDocuments.directory(root) where Self.isDirectory(url) { + result[url.lastPathComponent] = try antigravityBundle(at: url) + } + return result + } + + private func antigravityBundle(at root: URL) throws -> AntigravityBundle? { + guard let manifest = try Self.antigravityManifest(at: root) else { return nil } + let name = try manifest.hostValue(["name"])?.hostString ?? root.lastPathComponent + let disabled = try HostPluginDocuments.boolean(manifest.hostValue(["disabled"])) ?? false + return (name, root, disabled) + } + + static func antigravityManifest(at root: URL) throws -> NativeDocument? { + for path in [".antigravity-plugin/plugin.json", "plugin.json"] { + if let manifest = try HostPluginDocuments.read(root.appendingPathComponent(path)) { + return manifest + } + } + return nil + } + + private func antigravityEntries( + in file: URL, base: URL, depth: Int, visited: inout Set + ) throws -> [String: AntigravityBundle] { + guard depth < 16 else { + throw CoreError.invalidState("plugin discovery inheritance is too deep") + } + guard visited.insert(file.resolvingSymlinksInPath().path).inserted, + let manifest = try HostPluginDocuments.read(file) + else { return [:] } + func resolved(_ text: String) -> URL { + text.hasPrefix("/") + ? URL(fileURLWithPath: text).standardizedFileURL + : base.appendingPathComponent(text).standardizedFileURL + } + var result: [String: AntigravityBundle] = [:] + for key in ["entries", "inherits"] { + for entry in try HostPluginDocuments.list(manifest.hostValue([key])) { + let fields = try HostPluginDocuments.fields(entry) + guard let path = fields["path"]?.hostString, !path.isEmpty else { continue } + let source = resolved(path) + let include = try HostPluginDocuments.strings(fields["include_only"]) + let exclude = try HostPluginDocuments.strings(fields["exclude"]) + let candidates: [String: AntigravityBundle] + if key == "inherits" { + let parent = source.deletingLastPathComponent() + let root = + parent.lastPathComponent == ".agents" ? parent.deletingLastPathComponent() : parent + candidates = try antigravityEntries( + in: source, base: root, depth: depth + 1, visited: &visited) + } else if let bundle = try antigravityBundle(at: source) { + candidates = [source.lastPathComponent: bundle] + } else { + candidates = try antigravityBundles(at: source) + } + for (id, bundle) in candidates + where result[id] == nil + && (include.isEmpty || include.contains(id)) && !exclude.contains(id) + { + result[id] = bundle + } + } + } + return result + } +} + +struct HostMarketplace { + let root: URL + let name: String + let paths: [String: URL] + + static func read(at root: URL, manifest: String) throws -> Self? { + let file = try PathSafety.resolvedChild(base: root, subpath: manifest) + guard let document = try HostPluginDocuments.read(file) else { return nil } + guard let name = try document.hostValue(["name"])?.hostString, + HostPluginDocuments.safeID(name), !name.contains("@") + else { throw CoreError.invalidState("marketplace has no valid name") } + let pluginRoot = try document.hostValue(["metadata", "pluginRoot"])?.hostString + let base = try PathSafety.resolvedChild(base: root, subpath: pluginRoot ?? ".") + var paths: [String: URL] = [:] + for entry in try HostPluginDocuments.list(document.hostValue(["plugins"])) { + let fields = try HostPluginDocuments.fields(entry) + guard let plugin = fields["name"]?.hostString, HostPluginDocuments.safeID(plugin), + !plugin.contains("@") + else { continue } + let path: String? + switch fields["source"] { + case .string(let relative): + path = relative + case .object(let source) where source["source"]?.hostString == "local": + path = source["path"]?.hostString + default: + path = nil + } + guard let path, !path.isEmpty, !path.contains("://") else { continue } + let directory = try PathSafety.resolvedChild(base: base, subpath: path) + guard paths.updateValue(directory, forKey: plugin + "@" + name) == nil else { + throw CoreError.invalidState("marketplace contains duplicate plugin IDs") + } + } + return .init(root: root, name: name, paths: paths) + } + + func localBundle(for id: String) throws -> URL? { + guard let path = paths[id], let rootPath = PathSafety.realPath(root.path), + let real = PathSafety.realPath(path.path), + PathSafety.isContained(URL(fileURLWithPath: real), in: URL(fileURLWithPath: rootPath)) + else { return nil } + return path + } +} diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginModels.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginModels.swift new file mode 100644 index 0000000..14f15d3 --- /dev/null +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginModels.swift @@ -0,0 +1,64 @@ +import AgentsCore +import Foundation + +public enum HostPluginDrift: String, Codable, Sendable { + case current, missing, enablement, unsupported, unverified +} + +public enum HostPluginOutcome: String, Codable, Sendable { + case installed, enabled, disabled, unchanged, unsupported, cliUnavailable, authRequired, timeout, + failed +} + +public struct HostPluginStatus: Codable, Equatable, Sendable { + public let agent: AgentID + public let scope: InstallScope + public let claudeScope: ClaudePluginScope? + public let name: String + public let pluginId: String? + public let desiredEnabled: Bool? + public let installed: Bool? + public let explicitEnabled: Bool? + public let effectiveEnabled: Bool? + public let locations: [URL] + public let drift: HostPluginDrift + public let diagnostic: String? +} + +public struct HostPluginConfigurationChange: Codable, Equatable, Sendable { + public let file: URL + public let key: [String] + public let before: HostPluginConfigurationValue? + public let after: HostPluginConfigurationValue +} + +/// The exact plugin-owned value changed by a sync plan. +public enum HostPluginConfigurationValue: Codable, Equatable, Sendable { + case boolean(Bool) + case strings([String]) + case appendPath(String) +} + +public struct HostPluginPreview: Codable, Equatable, Sendable { + public let status: HostPluginStatus + /// Each array starts with the executable, followed by its arguments. + public let commands: [[String]] + public let configurationChanges: [HostPluginConfigurationChange] +} + +public struct HostPluginSyncResult: Codable, Equatable, Sendable { + public let preview: HostPluginPreview + public let status: HostPluginStatus + /// Nil for a dry run. + public let outcome: HostPluginOutcome? + public let commandsRun: [[String]] + public let diagnostic: String? +} + +public enum HostPluginCommandResult: Equatable, Sendable { + case success, cliUnavailable, authRequired, timeout, failed +} + +public protocol HostPluginCommandRunner: Sendable { + func run(argv: [String], environment: RuntimeEnvironment) async -> HostPluginCommandResult +} diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift new file mode 100644 index 0000000..8e471a5 --- /dev/null +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift @@ -0,0 +1,167 @@ +import AgentsCore +import AgentsManifest +import Foundation + +struct HostPluginTarget { + let declaration: HostPluginDeclaration + let agent: AgentID + let scope: InstallScope + let id: String? + let bundle: URL? + let marketplaceName: String? + let marketplaceSource: String? + let issue: (HostPluginDrift, String)? + + var claudeScope: ClaudePluginScope? { + guard agent == .claudeCode else { return nil } + return declaration.claudeScope ?? (scope == .user ? .user : .project) + } + + static let supportedAgents: Set = [.codex, .claudeCode, .antigravity] + + static func load( + scope: InstallScope, agents: [AgentID]?, environment: RuntimeEnvironment + ) throws -> [Self] { + let store = StateStore(scope: scope, environment: environment) + let declaration = try store.loadDeclaration() + let recipients = Set(agents ?? AgentID.allCases) + let root = scope == .user ? store.directory : environment.projectDirectory + let groups = Dictionary(uniqueKeysWithValues: declaration.groups.map { ($0.name, $0) }) + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + var targets: [Self] = [] + var seenGroups = Set() + func permits(_ condition: DeclarationCondition?, agent: AgentID) -> Bool { + (condition?.agents?.contains(agent) ?? true) + && (condition?.scopes?.contains(scope) ?? true) + && (condition?.platforms?.contains(platform) ?? true) + } + func add(_ components: [ComponentDeclaration], agents selected: Set) { + for component in components { + guard case .hostPlugin(let plugin) = component else { continue } + for agent in plugin.agents where selected.contains(agent) { + targets.append( + resolve( + plugin, agent: agent, scope: scope, root: root, sources: declaration.sources, + environment: environment)) + } + } + } + func visit(_ use: GroupUseDeclaration, agents selected: Set) { + guard use.source == nil || use.source == ".", let group = groups[use.name] else { return } + let allowed = selected.filter { agent in + permits(use.condition, agent: agent) && permits(group.condition, agent: agent) + && seenGroups.insert(group.name + "\0" + agent.rawValue).inserted + } + guard !allowed.isEmpty else { return } + add(group.components, agents: allowed) + for nested in group.uses { visit(nested, agents: allowed) } + } + add(declaration.components, agents: recipients) + for use in declaration.uses { visit(use, agents: recipients) } + return targets + } + + private static func resolve( + _ declaration: HostPluginDeclaration, agent: AgentID, scope: InstallScope, root: URL, + sources: [String: SourceDeclaration], environment: RuntimeEnvironment + ) -> Self { + func target( + id: String? = nil, bundle: URL? = nil, marketplaceName: String? = nil, + marketplaceSource: String? = nil, issue: (HostPluginDrift, String)? = nil + ) -> Self { + .init( + declaration: declaration, agent: agent, scope: scope, id: id, bundle: bundle, + marketplaceName: marketplaceName, marketplaceSource: marketplaceSource, issue: issue) + } + guard supportedAgents.contains(agent) else { + return target(issue: (.unsupported, "This agent has no host plugin sync adapter.")) + } + do { + switch declaration.selector { + case .marketplace(let id, let marketplace): + let market = id.split(separator: "@", omittingEmptySubsequences: false) + let catalog = market.count == 2 ? String(market[1]) : nil + let source = marketplace.map { value in + if value.hasPrefix("~/") { + return environment.homeDirectory.appendingPathComponent(String(value.dropFirst(2))).path + } + let local = root.appendingPathComponent(value).standardizedFileURL + if value.hasPrefix(".") + || (!value.hasPrefix("/") && FileManager.default.fileExists(atPath: local.path)) + { + return local.path + } + return value + } + if agent == .antigravity { + guard source == nil else { + return target( + id: id, issue: (.unsupported, "Antigravity uses its host marketplace catalog.")) + } + return target(id: String(market[0])) + } + guard market.count == 2, market.allSatisfy({ HostPluginDocuments.safeID(String($0)) }) + else { + return target(id: id, issue: (.unsupported, "The host requires a plugin@marketplace ID.")) + } + return target(id: id, marketplaceName: catalog, marketplaceSource: source) + case .bundle(let alias, let path): + let source = sources[alias] + if alias != ".", source?.kind != .local || source?.requirement != nil { + return target( + issue: (.unverified, "Host plugin source has no locally readable checkout.")) + } + let sourceRoot = source?.localURL(environment: environment) ?? root + let discovery = try PathSafety.resolvedChild(base: sourceRoot, subpath: source?.path ?? ".") + let bundle = try PathSafety.resolvedChild(base: discovery, subpath: path) + guard let real = PathSafety.realPath(bundle.path), + let admitted = PathSafety.realPath(sourceRoot.path), + PathSafety.isContained(URL(fileURLWithPath: real), in: URL(fileURLWithPath: admitted)) + else { + return target(issue: (.unverified, "The contained plugin bundle could not be read.")) + } + if agent == .antigravity { + guard try HostPluginLocations.antigravityManifest(at: bundle) != nil else { + return target(issue: (.unsupported, "The bundle has no Antigravity plugin manifest.")) + } + let id = bundle.lastPathComponent + guard HostPluginDocuments.safeID(id) else { + return target( + issue: (.unsupported, "The Antigravity plugin directory has an invalid name.")) + } + return target(id: id, bundle: bundle) + } + let manifest = + agent == .codex + ? ".agents/plugins/marketplace.json" : ".claude-plugin/marketplace.json" + for directory in discovery.path == sourceRoot.path ? [sourceRoot] : [discovery, sourceRoot] + { + guard let catalog = try HostMarketplace.read(at: directory, manifest: manifest) else { + continue + } + let matches = try catalog.paths.keys.sorted().filter { id in + guard let location = try catalog.localBundle(for: id) else { return false } + return PathSafety.realPath(location.path) == real + } + if matches.count == 1 { + return target( + id: matches[0], bundle: bundle, marketplaceName: catalog.name, + marketplaceSource: catalog.root.path) + } + if matches.count > 1 { + return target( + issue: (.unsupported, "Multiple marketplace IDs refer to this plugin bundle.")) + } + } + return target( + issue: (.unsupported, "No host marketplace entry identifies this plugin bundle.")) + } + } catch { + return target(issue: (.unverified, "Host plugin source metadata could not be read.")) + } + } +} diff --git a/Sources/AgentsUpdates/HostPlugins/SkillGovernance.swift b/Sources/AgentsUpdates/HostPlugins/SkillGovernance.swift new file mode 100644 index 0000000..735ff34 --- /dev/null +++ b/Sources/AgentsUpdates/HostPlugins/SkillGovernance.swift @@ -0,0 +1,310 @@ +import AgentsCore +import AgentsSkills +import Foundation + +public struct SkillGovernanceCheck: Codable, Equatable, Sendable { + public let id: String + public let status: DoctorCheckStatus + public let agent: AgentID + public let message: String + public let path: String? + public let relatedPath: String? + public let collision: SkillPluginCollision? +} + +public enum SkillPluginCollision: String, Codable, Sendable { + case sameTarget, divergentTarget, basenameOverlap +} + +public struct SkillListingBudget: Codable, Equatable, Sendable { + public let agent: AgentID + public let skills: Int + public let utf8Bytes: Int + public let advisoryThreshold: Int + public let estimate: String +} + +public struct SkillGovernanceReport: Codable, Equatable, Sendable { + public let checks: [SkillGovernanceCheck] + public let hostPlugins: [HostPluginStatus] + public let skillBudgets: [SkillListingBudget]? + public let recoveryPending: Bool +} + +/// Read-only governance for a runtime root. No local or remote CLI is used as an authority. +public enum SkillGovernance { + public static func inspect( + scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = .init() + ) throws -> SkillGovernanceReport { + let store = StateStore(scope: scope, environment: environment) + let ledger = try store.withReadLock( + onPendingRecovery: { nil }, + { + try Optional(store.readLedger()) + }) + guard let ledger else { + return .init(checks: [], hostPlugins: [], skillBudgets: nil, recoveryPending: true) + } + let hostPlugins: [HostPluginStatus] + do { + hostPlugins = try HostPluginExecutor.inspect( + scope: scope, agents: agents, environment: environment, includeUnmanaged: false) + } catch CoreError.recoveryPending { + return .init(checks: [], hostPlugins: [], skillBudgets: nil, recoveryPending: true) + } + + var checks: [SkillGovernanceCheck] = [] + var budgets: [SkillListingBudget] = [] + let selected = Set(agents ?? AgentID.allCases) + for status in hostPlugins where status.drift != .current { + let message = + status.diagnostic ?? "Host plugin '\(status.name)' is \(status.drift.rawValue)." + checks.append( + check( + "host-plugin-" + status.drift.rawValue, agent: status.agent, message: message, + path: status.locations.first?.path)) + } + if scope == .user, selected.contains(.codex) { + checks += try legacyCodex(ledger: ledger, store: store) + } + + let includeInternal = environment.environment["INSTALL_INTERNAL_SKILLS"] == "1" + let locations = HostPluginLocations(environment: environment) + for agent in AgentID.allCases where selected.contains(agent) { + let standalone = try standaloneSkills( + agent: agent, environment: environment, includeInternal: includeInternal) + let plugins: [PluginSkill] + do { + plugins = try pluginSkills( + agent: agent, locations: locations, includeInternal: includeInternal) + } catch { + // The inventory provides no reliable effective enablement for this host. + if !checks.contains(where: { $0.agent == agent && $0.id == "host-plugin-unverified" }) { + checks.append( + check( + "host-plugin-unverified", agent: agent, + message: "Host plugin inventory could not be read.")) + } + continue + } + checks += collisions(agent: agent, standalone: standalone, plugins: plugins) + if let estimate = budget( + agent: agent, standalone: standalone, plugins: plugins, environment: environment) + { + budgets.append(estimate) + if estimate.utf8Bytes > estimate.advisoryThreshold { + checks.append( + check( + "skill-listing-budget", agent: agent, + message: + "\(agent.displayName) skill listing estimate is \(estimate.utf8Bytes) UTF-8 bytes, above the advisory threshold of \(estimate.advisoryThreshold)." + )) + } + } + } + return .init( + checks: checks, hostPlugins: hostPlugins, skillBudgets: budgets.isEmpty ? nil : budgets, + recoveryPending: false) + } + + private static func check( + _ id: String, agent: AgentID, message: String, path: String? = nil, + relatedPath: String? = nil, collision: SkillPluginCollision? = nil + ) -> SkillGovernanceCheck { + .init( + id: id, status: .warning, agent: agent, message: message, path: path, + relatedPath: relatedPath, collision: collision) + } + + private static func legacyCodex( + ledger: ResolvedLedger, store: StateStore + ) throws -> [SkillGovernanceCheck] { + let roots = store.ledgerRoots(recordedIn: ledger) + let skills = ledger.deployments.filter { $0.route == "agents/skill@1" } + let owned = try Set( + skills.map { record in + SkillLifecycle.physicalTarget(try record.target.resolve(roots: roots)).path + }) + let shared = AgentRegistry.canonicalSkillsDirectory( + scope: .user, environment: store.environment) + return try skills.filter { $0.target.root == "skills-codex-private" }.sorted { + $0.target.path.utf8.lexicographicallyPrecedes($1.target.path.utf8) + }.compactMap { privateSkill in + let target = try privateSkill.target.resolve(roots: roots) + let legacy = SkillLifecycle.physicalTarget( + shared.appendingPathComponent(privateSkill.target.path)) + guard PathSafety.realPath(target.appendingPathComponent("SKILL.md").path) != nil, + !owned.contains(legacy.path), + (try? FileManager.default.destinationOfSymbolicLink(atPath: legacy.path)) != nil, + PathSafety.realPath(legacy.appendingPathComponent("SKILL.md").path) != nil + else { return nil } + return check( + "codex-legacy-skill-link", agent: .codex, + message: + "An unmanaged shared link makes Codex skill '\(privateSkill.target.path)' visible outside its private directory.", + path: legacy.path, relatedPath: target.path) + } + } + + private struct LocatedSkill { + let skill: Skill + let physical: String + } + + private struct PluginSkill { + let content: LocatedSkill + let namespace: String + let root: URL + let opaqueClaudeRoot: Bool + + func name(for agent: AgentID) -> String { + agent == .antigravity ? namespace + ":" + content.skill.name : content.skill.name + } + } + + private static func standaloneSkills( + agent: AgentID, environment: RuntimeEnvironment, includeInternal: Bool + ) throws -> [LocatedSkill] { + let project = AgentRegistry.projectScanDirectories(for: agent, environment: environment) + let user = AgentRegistry.nativeUserScanDirectories(for: agent, environment: environment) + let roots = agent == .claudeCode ? user + project : project + user + var visited = Set() + var result: [LocatedSkill] = [] + for root in roots { + for skill in try SkillOperations.governanceSkills(in: root, includeInternal: includeInternal) + { + guard let physical = PathSafety.realPath(skill.skillFile), visited.insert(physical).inserted + else { continue } + result.append(.init(skill: skill, physical: physical)) + } + } + return result + } + + private static func pluginSkills( + agent: AgentID, locations: HostPluginLocations, includeInternal: Bool + ) throws -> [PluginSkill] { + let inventory = try locations.inventory(agent: agent, scope: .project) + var bundles: [(namespace: String, root: URL, opaqueClaude: Bool)] = [] + if agent == .claudeCode { + let environment = locations.environment + let roots = + AgentRegistry.nativeUserScanDirectories(for: agent, environment: environment) + + AgentRegistry.projectScanDirectories(for: agent, environment: environment) + for root in roots { + for bundle in try HostPluginDocuments.directory(root) { + guard + (try? bundle.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true + || FileManager.default.fileExists( + atPath: bundle.appendingPathComponent(".claude-plugin").path) + else { continue } + guard + let manifest = try HostPluginDocuments.read( + bundle.appendingPathComponent(".claude-plugin/plugin.json")) + else { continue } + let name = try manifest.hostValue(["name"])?.hostString ?? bundle.lastPathComponent + bundles.append((name, bundle, true)) + } + } + } + for plugin in inventory.plugins.values.sorted(by: { $0.id < $1.id }) + where plugin.effective == true { + if let location = plugin.locations.first { bundles.append((plugin.name, location, false)) } + } + var seen = Set() + var result: [PluginSkill] = [] + for bundle in bundles { + var skills = try SkillOperations.governanceSkills( + in: bundle.root.appendingPathComponent("skills"), includeInternal: includeInternal) + if agent == .claudeCode { + let manifest = try HostPluginDocuments.read( + bundle.root.appendingPathComponent(".claude-plugin/plugin.json")) + let value = try manifest?.hostValue(["skills"]) + let paths = try value?.hostString.map { [$0] } ?? HostPluginDocuments.strings(value) + for path in paths { + let root = try PathSafety.resolvedChild(base: bundle.root, subpath: path) + if let skill = try SkillOperations.parseGovernanceSkill( + at: root, includeInternal: includeInternal) + { + skills.append(skill) + } else { + skills += try SkillOperations.governanceSkills( + in: root, includeInternal: includeInternal) + } + } + } + for skill in skills { + guard let physical = PathSafety.realPath(skill.skillFile), + seen.insert(physical + "\0" + bundle.namespace).inserted + else { continue } + result.append( + .init( + content: .init(skill: skill, physical: physical), namespace: bundle.namespace, + root: bundle.root, opaqueClaudeRoot: bundle.opaqueClaude)) + } + } + return result + } + + private static func collisions( + agent: AgentID, standalone: [LocatedSkill], plugins: [PluginSkill] + ) -> [SkillGovernanceCheck] { + let names = Dictionary(grouping: standalone, by: { $0.skill.name }) + var checks: [SkillGovernanceCheck] = [] + for plugin in plugins { + let name = plugin.name(for: agent) + let base = plugin.content.skill.name + let exact = (names[name] ?? []).map { ($0, true) } + let overlaps = agent == .antigravity ? (names[base] ?? []).map { ($0, false) } : [] + for (skill, matches) in exact + overlaps { + if plugin.opaqueClaudeRoot, + PathSafety.isContained(URL(fileURLWithPath: skill.skill.path), in: plugin.root) + { + continue + } + let collision: SkillPluginCollision = + matches + ? (skill.physical == plugin.content.physical ? .sameTarget : .divergentTarget) + : .basenameOverlap + let detail: String + switch collision { + case .sameTarget: detail = "register the same skill file twice" + case .divergentTarget: detail = "register different skill files under the same name" + case .basenameOverlap: detail = "share a basename with distinct Antigravity skill names" + } + checks.append( + check( + "plugin-skill-" + collision.rawValue, agent: agent, + message: "Standalone skill '\(skill.skill.name)' and plugin skill '\(name)' \(detail).", + path: skill.skill.skillFile, relatedPath: plugin.content.skill.skillFile, + collision: collision)) + } + } + return checks + } + + private static func budget( + agent: AgentID, standalone: [LocatedSkill], plugins: [PluginSkill], + environment: RuntimeEnvironment + ) -> SkillListingBudget? { + var names = Set() + var bytes = 0 + let listing = + standalone.map { ($0.skill.name, $0.skill.description) } + + plugins.map { ($0.name(for: agent), $0.content.skill.description) } + for (name, description) in listing where names.insert(name).inserted { + bytes += name.utf8.count + description.utf8.count + } + guard !names.isEmpty else { return nil } + let override = + agent == .claudeCode + ? environment.environment["SLASH_COMMAND_TOOL_CHAR_BUDGET"].flatMap(Int.init) : nil + let threshold = override.flatMap { $0 >= 0 ? $0 : nil } ?? 8_000 + return .init( + agent: agent, skills: names.count, utf8Bytes: bytes, advisoryThreshold: threshold, + estimate: + "Estimated UTF-8 bytes of skill names and descriptions, excluding host built-ins and per-skill framing." + ) + } +} diff --git a/Sources/AgentsUpdates/ProducerPatchRoutes.swift b/Sources/AgentsUpdates/ProducerPatchRoutes.swift index f292ad5..af73987 100644 --- a/Sources/AgentsUpdates/ProducerPatchRoutes.swift +++ b/Sources/AgentsUpdates/ProducerPatchRoutes.swift @@ -66,7 +66,10 @@ struct ProducerPatchRoutes { continue } guard let agent = record.recipients.first, record.recipients == [agent], - record.target.kind == .registered, record.target.root == "skills-" + agent.rawValue, + record.target.kind == .registered, let root = record.target.root, + AgentRegistry.skillRoot( + root, scope: inputs.store.scope, environment: inputs.store.environment)? + .agent == agent, lowering.inputs == record.owners, lowering.resources.count == 1, let owner = ledger.components[record.owners[0]], owner.kind == "skills", owner.recipients.contains(agent), owner.resources == lowering.resources, @@ -83,7 +86,8 @@ struct ProducerPatchRoutes { skip(reason) continue } - let target = try inputs.store.skillInstallationTarget(for: agent, named: record.target.path) + let target = try inputs.store.skillInstallationTarget( + for: agent, named: record.target.path, root: root) installations[target.url.path] = target routes.formUnion(target.footprint) // The recorded loader spelling is read with no-follow even if it has a coordination alias. diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index ef88f70..1a65ba7 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -222,7 +222,7 @@ final class UpdatePlan { request.selectedIdentities = try MarketplaceGraphChange.deploymentIdentities( from: previous, to: next, roots: roots) } else { - next = previous + next = DeploymentConstruction.retargetLegacyCodexSkills(previous, scope: store.scope) } try MarketplaceGraphChange.validateHosted( next.marketplaceGraph, objects: next.contentObjects, policy: sourcePolicy.effective, @@ -841,7 +841,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 { + if try store.declarationBytes(prepared: baseline) != nil || declarationChange != nil + || previous.deployments != next.deployments + { try store.stageLedger( producing: { self.aggregation.ledger }, limits: .standard, transaction: transaction, prepared: baseline) @@ -1201,6 +1203,7 @@ final class UpdatePlan { extension ComponentDeclaration { fileprivate var selectedAgents: [AgentID]? { switch self { + case .hostPlugin(let value): value.agents case .skills(_, let s): s.agents case .instructions(let s): s.agents case .mcpServer(_, _, let a, _, _, _), .hook(_, _, _, _, _, let a, _, _), @@ -1242,6 +1245,9 @@ extension ComponentDeclaration { 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 .hostPlugin(var value): + value.agents = agents + return .hostPlugin(value) 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, diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift index ae8049e..27688e8 100644 --- a/Sources/AgentsUpdates/UpdateReporting.swift +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -17,11 +17,23 @@ enum UpdateReporting { let name: String var record: LockedSkill let resource: String + var paths: [String: 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 { + var locations: [String: [String: String]] = [:] + for deployment in ledger.deployments where deployment.route == "agents/skill@1" { + let target = try deployment.target.resolve(roots: roots) + let path = target.path + for owner in deployment.owners { + for agent in deployment.recipients { + locations[owner, default: [:]][agent.rawValue] = path + } + } + } + for id in ledger.components.keys.sorted() { + let component = ledger.components[id]! + guard component.kind == "skills", !component.recipients.isEmpty else { continue } if let selectedIdentities, !selectedIdentities.contains( try LedgerImpact.identity(component, ledger: ledger, roots: roots)) @@ -31,7 +43,9 @@ enum UpdateReporting { guard names.isEmpty || names.contains(PathSafety.sanitizeName(component.name)) else { continue } - guard let id = component.resources.first, let resource = ledger.resources[id] else { + guard let resourceID = component.resources.first, + let resource = ledger.resources[resourceID] + else { continue } let source = try ledger.sourceIdentity(component.source, roots: roots) @@ -55,8 +69,12 @@ enum UpdateReporting { 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 } + let paths = (result[identity]?.paths ?? [:]).merging(locations[id] ?? [:]) { first, _ in + first + } result[identity] = Item( - name: PathSafety.sanitizeName(component.name), record: record, resource: id) + name: PathSafety.sanitizeName(component.name), record: record, resource: resourceID, + paths: paths) } return result } @@ -67,19 +85,34 @@ enum UpdateReporting { 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) + .flatMap { raw -> [SkillMembershipChange] in + guard let agent = AgentID(rawValue: raw) else { return [] } + let fallback = SkillLifecycle.target(name: name, agent: agent, store: store).path + let prior = before[identity]?.paths[raw] + let next = after[identity]?.paths[raw] + let beforeState = + old?.installs[raw].map { SkillMembership.installed(mode: $0) } ?? .absent + let afterState = new?.installs[raw].map { SkillMembership.installed(mode: $0) } ?? .absent + if let prior, let next, prior != next, + InstructionLocations.physical(URL(fileURLWithPath: prior)).path + != InstructionLocations.physical(URL(fileURLWithPath: next)).path + { + return [ + SkillMembershipChange(agent: agent, path: prior, before: beforeState, after: .absent), + SkillMembershipChange(agent: agent, path: next, before: .absent, after: afterState), + ] + } + return [ + SkillMembershipChange( + agent: agent, path: next ?? prior ?? fallback, before: beforeState, after: afterState) + ] } 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) + path: after[identity]?.paths[raw] + ?? SkillLifecycle.target(name: name, agent: agent, store: store).path) } let content = after[identity].flatMap { resources[$0.resource] } var diffs: [SkillFileChange] = [] @@ -88,7 +121,7 @@ enum UpdateReporting { } for target in physicalMembers.keys.sorted() { let members = physicalMembers[target]! - let retained = members.contains { new?.installs[$0.agent.rawValue] != nil } + let retained = members.contains { $0.after != .absent } 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 }) { diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index d31df3e..bf5b163 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -249,12 +249,49 @@ package final class ArtifactAggregation: PreparedEvidence { byPath.removeValue(forKey: path) } } + let privateCodex = Set( + ledger.deployments.filter { + $0.route == "agents/skill@1" && $0.target.root == "skills-codex-private" + }.map(\.target.path)) + let migratingCodex = Set( + previous.deployments.compactMap { deployment -> String? in + guard store.scope == .user, deployment.route == "agents/skill@1", + deployment.target.root == "skills-codex" + else { return nil } + let name = PathSafety.sanitizeName(deployment.target.path) + return privateCodex.contains(name) ? name : nil + }) 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] ?? [] + if store.scope == .user, capture.exists, + let legacy = old.first(where: { + $0.route == "agents/skill@1" && $0.target.root == "skills-codex" + }), + privateCodex.contains(PathSafety.sanitizeName(legacy.target.path)) + { + let observed = try Self.inspectDeployment( + legacy, ledger: previous, store: store, roots: roots) + let lowering = previous.lowerings.first { $0.deployments.contains(legacy.id) } + let mode = lowering?.layout.object?["mode"]?.text + let verifiedTarget: Bool + if mode == InstallMode.link.rawValue, let resource = lowering?.resources.first { + verifiedTarget = try PathSafety.matchesSymbolicLink( + at: url, destination: resourceDestination(resource, in: previous)) + } else if mode == InstallMode.copy.rawValue { + verifiedTarget = + (try? FileManager.default.destinationOfSymbolicLink(atPath: url.path)) == nil + } else { + verifiedTarget = mode == InstallMode.edit.rawValue + } + if observed.status != "current" || !verifiedTarget { + unownedSkills.append("legacy Codex skill could not be verified at \(path)") + continue + } + } if verifyPriorSkillLinks, capture.exists, let prior = old.first(where: { $0.route == "agents/skill@1" }), let lowering = previous.lowerings.first(where: { $0.deployments.contains(prior.id) }), @@ -334,7 +371,13 @@ package final class ArtifactAggregation: PreparedEvidence { { resourceEvidence.append(try TargetPrecondition(URL(fileURLWithPath: resolved))) } - if old.isEmpty, FileManager.default.fileExists(atPath: path) { + let migratingIntoPrivateCodex = + deployment.target.root == "skills-codex-private" + && migratingCodex.contains(deployment.target.path) + if old.isEmpty, + FileManager.default.fileExists(atPath: path) + || (migratingIntoPrivateCodex && capture.exists) + { unownedSkills.append( "skill '\(ledger.components[deployment.owners[0]]!.name)' in \(store.scope.rawValue) scope has unmanaged content at \(path); move or remove it first" ) @@ -504,10 +547,11 @@ package final class ArtifactAggregation: PreparedEvidence { guard deployment.route == "agents/skill@1" else { return InstructionLocations.physical(try deployment.target.resolve(roots: roots)) } - guard let agent = deployment.recipients.first else { + guard let agent = deployment.recipients.first, let root = deployment.target.root else { throw CoreError.invalidState("missing skill recipient") } - let target = try store.skillInstallationTarget(for: agent, named: deployment.target.path) + let target = try store.skillInstallationTarget( + for: agent, named: deployment.target.path, root: root) guard let admitted = skillTargets[target.url.path] else { throw CoreError.invalidState("skill installation was not admitted") } diff --git a/Sources/Components/ComponentFields.swift b/Sources/Components/ComponentFields.swift index f9ac103..b7a9e0f 100644 --- a/Sources/Components/ComponentFields.swift +++ b/Sources/Components/ComponentFields.swift @@ -4,6 +4,7 @@ extension ComponentDeclaration { package var name: String? { switch self { case .skills, .instructions: nil + case .hostPlugin(let value): value.name case .mcpServer(let name, _, _, _, _, _), .hook(let name, _, _, _, _, _, _, _), .subagent(let name, _, _, _, _, _, _, _), .command(let name, _, _, _, _, _, _), .lspServer(let name, _, _, _, _, _, _), .permissions(let name, _, _, _, _), @@ -14,6 +15,7 @@ extension ComponentDeclaration { var agents: [AgentID]? { switch self { + case .hostPlugin(let value): value.agents case .skills(_, let value): value.agents case .instructions(let value): value.agents case .mcpServer(_, _, let agents, _, _, _), .hook(_, _, _, _, _, let agents, _, _), @@ -26,6 +28,7 @@ extension ComponentDeclaration { var condition: DeclarationCondition? { switch self { + case .hostPlugin: nil case .skills(_, let value): value.condition case .instructions(let value): value.condition case .mcpServer(_, _, _, let condition, _, _), .hook(_, _, _, _, _, _, let condition, _), @@ -103,6 +106,7 @@ extension ComponentDeclaration { 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 .hostPlugin: return self case .plugin( let name, let path, _, let mode, let select, let exclude, _, _, let native): return .plugin( diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift index 7940eaa..7119881 100644 --- a/Sources/Components/DeploymentConstruction.swift +++ b/Sources/Components/DeploymentConstruction.swift @@ -3,6 +3,23 @@ import AgentsInstructions import Foundation package enum DeploymentConstruction { + package static func retargetLegacyCodexSkills( + _ previous: ResolvedLedger, scope: InstallScope + ) -> ResolvedLedger { + guard scope == .user else { return previous } + var next = previous + for index in next.deployments.indices { + let deployment = next.deployments[index] + if deployment.route == "agents/skill@1", deployment.target.kind == .registered, + deployment.target.root == "skills-codex", deployment.recipients == [.codex] + { + next.deployments[index].target.root = AgentRegistry.skillRootKey(for: .codex, scope: scope) + next.deployments[index].target.path = PathSafety.sanitizeName(deployment.target.path) + } + } + return next + } + package static func validateCopiedSkill(_ tree: URL) throws { guard let real = PathSafety.realPath(tree.path), let children = FileManager.default.enumerator( @@ -332,7 +349,7 @@ package enum DeploymentConstruction { add( id: id, format: "agents/skill@1", inputs: [key], resources: record.resources, location: .init( - kind: .registered, root: "skills-" + agent.rawValue, + kind: .registered, root: AgentRegistry.skillRootKey(for: agent, scope: store.scope), path: PathSafety.sanitizeName(component.key.name)), agents: [agent], hash: resource.hash, layout: ["name": .init(id), "mode": record.payload.object!["mode"]!]) diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index e144cc9..2740645 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -236,6 +236,7 @@ final class Expansion { } private func includes(_ component: ComponentDeclaration) -> Bool { + guard component.kind != .hostPlugin else { return false } guard linking.instructionsOnly else { return true } // Supported native container profiles do not convert rules or context files to instructions. return component.kind == .instructions diff --git a/Sources/Components/Import/ImportSkillContent.swift b/Sources/Components/Import/ImportSkillContent.swift index bd13147..e8648fc 100644 --- a/Sources/Components/Import/ImportSkillContent.swift +++ b/Sources/Components/Import/ImportSkillContent.swift @@ -20,7 +20,10 @@ struct ImportSkillContent { let directory = try source.resource(path) let boundary: URL if let nativeContainer { - guard [.claudePluginV1, .cursorPluginV1, .geminiExtensionV1].contains(input.profile) else { + guard + [.agentPluginV1, .claudePluginV1, .cursorPluginV1, .geminiExtensionV1].contains( + input.profile) + else { throw ImportReadFailure.invalid } boundary = try source.resource(ImportInput.path(nativeContainer)) diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index 6618d60..f7d577f 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -9,6 +9,7 @@ enum NativeContainerImport { ) throws { let suffix: String switch input.profile { + case .agentPluginV1: suffix = "plugin.json" case .claudePluginV1: suffix = ".claude-plugin/plugin.json" case .cursorPluginV1: suffix = ".cursor-plugin/plugin.json" default: suffix = "gemini-extension.json" @@ -29,6 +30,22 @@ enum NativeContainerImport { let agent = NativeImportInput.agent(input.profile) let alias = NativeImportInput.source( input, root: root, origin: parsed.location(), into: &diagnostics) + if input.profile == .agentPluginV1 { + guard parsed.fields["$schema"]?.importString == AgentPluginManifest.schema else { + throw ImportReadFailure.invalid + } + let version = parsed.fields["version"]?.importString + diagnostics.proposal.packageMetadata = .init( + name: name, version: version, nameLocation: parsed.fieldLocation(["name"]), + versionLocation: version.map { _ in parsed.fieldLocation(["version"]) }, + description: parsed.fields["description"]?.importString, + author: parsed.fields["author"]?.importObject?.compactMapValues(\.importString), + keywords: parsed.fields["keywords"]?.importStrings) + try discover( + "skills", kind: .skills, root: root, input: input, limits: limits, into: &diagnostics, + admission: parsed.admission, requiredOrigin: nil) + return + } let surface = NativeImportSemantics.surface(input.profile) let defaults: [String: String] do { diff --git a/Sources/Components/Import/NativeSourceImport.swift b/Sources/Components/Import/NativeSourceImport.swift index 3aac7fc..9a5be39 100644 --- a/Sources/Components/Import/NativeSourceImport.swift +++ b/Sources/Components/Import/NativeSourceImport.swift @@ -24,7 +24,7 @@ enum NativeSourceImport { profile: input.profile, into: &diagnostics) try NativeImportInput.resource( input.document, root: ".", input: input, origin: origin, limits: limits, into: &diagnostics) - case .claudePluginV1, .cursorPluginV1, .geminiExtensionV1: + case .agentPluginV1, .claudePluginV1, .cursorPluginV1, .geminiExtensionV1: try NativeContainerImport.read(input, limits: limits, into: &diagnostics) case .claudeMarketplaceV1: try NativeCatalogImport.read(input, limits: limits, into: &diagnostics) diff --git a/Sources/Components/Import/SourceImport.swift b/Sources/Components/Import/SourceImport.swift index 03c4182..b9bd455 100644 --- a/Sources/Components/Import/SourceImport.swift +++ b/Sources/Components/Import/SourceImport.swift @@ -56,7 +56,7 @@ package enum SourceImport { try RulesyncSourceImport.read( ImportInput.document(input, limits: limits), input: input, into: &diagnostics) case .claudeSettingsV1, .codexConfigV1, .cursorMCPV1, .geminiSettingsV1, .openCodeConfigV2, - .claudePluginV1, .cursorPluginV1, .geminiExtensionV1, .claudeMarketplaceV1, + .agentPluginV1, .claudePluginV1, .cursorPluginV1, .geminiExtensionV1, .claudeMarketplaceV1, .claudeCommandV1, .claudeAgentV1, .geminiCommandV1, .geminiAgentV1, .openCodeCommandV2, .openCodeAgentV2, .cursorCommandV1, .cursorAgentV1, .geminiIgnoreV1, .cursorIgnoreV1: diff --git a/Sources/Components/Import/SourceImportProposal.swift b/Sources/Components/Import/SourceImportProposal.swift index 82d2dd2..4a25d27 100644 --- a/Sources/Components/Import/SourceImportProposal.swift +++ b/Sources/Components/Import/SourceImportProposal.swift @@ -6,7 +6,7 @@ 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 agentPluginV1, claudePluginV1, cursorPluginV1, geminiExtensionV1, claudeMarketplaceV1 case claudeCommandV1, claudeAgentV1, geminiCommandV1, geminiAgentV1 case openCodeCommandV2, openCodeAgentV2, cursorCommandV1, cursorAgentV1 case geminiIgnoreV1, cursorIgnoreV1 @@ -17,6 +17,7 @@ package enum SourceImportProfile: String, Sendable { case .rulesyncSourcesV1, .rulesyncNpmV1, .rulesyncConfig, .rulesyncGitHubV1, .rulesyncAPMV1, .vercelProjectV2, .vercelUserV3: "Pinned producer implementation format" + case .agentPluginV1: "Agent Plugins 1.0.0" case .codexConfigV1: "Pinned Codex source format" case .geminiSettingsV1, .geminiExtensionV1, .geminiCommandV1, .geminiAgentV1, .geminiIgnoreV1: "Pinned Gemini CLI source format" @@ -44,7 +45,8 @@ package enum SourceImportProfile: String, Sendable { "5a5c7180ff3f0a02511f54b54db7f228d4982a30" case .openCodeConfigV2, .openCodeCommandV2, .openCodeAgentV2: "fedc6f208aa2bd54c1019227214568083f6380ad" - case .claudeSettingsV1, .claudePluginV1, .claudeMarketplaceV1, .claudeCommandV1, .claudeAgentV1, + case .agentPluginV1, .claudeSettingsV1, .claudePluginV1, .claudeMarketplaceV1, .claudeCommandV1, + .claudeAgentV1, .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, .cursorAgentV1, .cursorIgnoreV1: nil } @@ -191,6 +193,9 @@ package struct ImportResourceProposal: Equatable, Sendable { package struct ImportPackageMetadata: Equatable, Sendable { package let name: String package let version: String? + package let description: String? + package let author: [String: String]? + package let keywords: [String]? package let nameLocation: ImportLocation package let versionLocation: ImportLocation? @@ -198,14 +203,21 @@ package struct ImportPackageMetadata: Equatable, Sendable { self.name = name self.nameLocation = nameLocation version = nil + description = nil + author = nil + keywords = nil versionLocation = nil } package init( - name: String, version: String, nameLocation: ImportLocation, versionLocation: ImportLocation + name: String, version: String?, nameLocation: ImportLocation, versionLocation: ImportLocation?, + description: String? = nil, author: [String: String]? = nil, keywords: [String]? = nil ) { self.name = name self.version = version + self.description = description + self.author = author + self.keywords = keywords self.nameLocation = nameLocation self.versionLocation = versionLocation } diff --git a/Sources/Components/LedgerPayload.swift b/Sources/Components/LedgerPayload.swift index cb91714..81ce9e5 100644 --- a/Sources/Components/LedgerPayload.swift +++ b/Sources/Components/LedgerPayload.swift @@ -57,6 +57,9 @@ package enum LedgerPayload { "name": .init(name), "patterns": strings(patterns), "purpose": .init(purpose.rawValue), ] (agents, condition, native) = (a, c, n) + case .hostPlugin: + throw CoreError.invalidState( + "host plugin declarations are outside the resolved deployment graph") case .plugin( let name, let path, let source, let mode, let select, let exclude, let a, let c, let n): fields = [ diff --git a/Sources/Components/NativeGeneratedPluginLayoutV1.swift b/Sources/Components/NativeGeneratedPluginLayoutV1.swift index 63eccd2..d1ad111 100644 --- a/Sources/Components/NativeGeneratedPluginLayoutV1.swift +++ b/Sources/Components/NativeGeneratedPluginLayoutV1.swift @@ -155,8 +155,11 @@ package enum NativeGeneratedPluginLayoutV1 { 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), + [ + "native/agentPluginV1@1", "native/claudePluginV1@1", "native/cursorPluginV1@1", + "native/geminiExtensionV1@1", + ] + .contains(expansion.input.format), expansion.input.adapterVersion == "1" else { throw input.issue( diff --git a/Sources/Components/PluginExpansion.swift b/Sources/Components/PluginExpansion.swift index 7f59622..d47cfff 100644 --- a/Sources/Components/PluginExpansion.swift +++ b/Sources/Components/PluginExpansion.swift @@ -1,5 +1,6 @@ import AgentsCore import Foundation +import NativeDocuments extension Expansion { func plugin( @@ -40,16 +41,7 @@ extension Expansion { 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 - } + let entries = try PluginManifestSelection.entries(in: view, container: container) guard entries.count == 1, let (profile, document) = entries.first else { throw LinkError.invalid("plugin requires one supported native container manifest", chain) } @@ -260,3 +252,47 @@ extension Expansion { } } } + +enum PluginManifestSelection { + static func entries( + in view: SourceSnapshot, container: String + ) throws -> [(SourceImportProfile, String)] { + func path(_ suffix: String) -> String { container == "." ? suffix : container + "/" + suffix } + func document(_ relative: String) throws -> NativeDocument? { + guard let bytes = try FileSystem.readUnlessDenied(at: view.resource(relative)) else { + return nil + } + return try NativeDocument( + bytes: bytes, format: .json, budget: NativeImportBudget(.init()).parser) + } + let claude = path(".claude-plugin/plugin.json") + let portable = path("plugin.json") + var entries: [(SourceImportProfile, String)] = [] + for (profile, suffix) in [ + (SourceImportProfile.claudePluginV1, ".claude-plugin/plugin.json"), + (.cursorPluginV1, ".cursor-plugin/plugin.json"), + (.geminiExtensionV1, "gemini-extension.json"), + ] { + let relative = path(suffix) + if FileManager.default.fileExists(atPath: try view.resource(relative).path) { + entries.append((profile, relative)) + } + } + if let root = try? document(portable), + try root.read(.init(keys: ["$schema"]))?.value == .string(AgentPluginManifest.schema) + { + if entries.contains(where: { $0.0 == .claudePluginV1 }) { + let native = try document(claude) + if let lhs = try native?.read(.init(keys: ["name"]))?.value, + let rhs = try root.read(.init(keys: ["name"]))?.value, lhs != rhs + { + throw CoreError.invalidSource( + "Claude and Agent Plugins manifests declare different names") + } + } else { + entries.append((.agentPluginV1, portable)) + } + } + return entries + } +} diff --git a/Sources/Components/SourceCatalog.swift b/Sources/Components/SourceCatalog.swift index 051f1c6..66c4400 100644 --- a/Sources/Components/SourceCatalog.swift +++ b/Sources/Components/SourceCatalog.swift @@ -286,27 +286,27 @@ package struct SourceCatalog: Sendable { 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 - } + let plugins = try PluginManifestSelection.entries(in: view, container: view.discoveryPath) + guard plugins.count <= 1 else { + throw CoreError.invalidSource("multiple native container manifests") + } + for (profile, document) in plugins { + let agent = NativeImportInput.agent(profile) 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: proposal.packageMetadata?.nameLocation ?? .init(document: document, pointer: ""), - unavailable: nativeName == nil - ? "native registration requires adapter-issued container name metadata" : nil) + if profile != .agentPluginV1 { + try resolved( + .nativePlugin(native), component: native, + label: "Native \(agent.rawValue) registration", + origin: proposal.packageMetadata?.nameLocation + ?? .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 diff --git a/Tests/AgentsCoreTests/AgentRegistryTests.swift b/Tests/AgentsCoreTests/AgentRegistryTests.swift index eb4603a..41ea2b2 100644 --- a/Tests/AgentsCoreTests/AgentRegistryTests.swift +++ b/Tests/AgentsCoreTests/AgentRegistryTests.swift @@ -64,8 +64,18 @@ struct AgentRegistryTests { AgentRegistry.canonicalSkillsDirectory(scope: .user, environment: environment).path == home.appendingPathComponent(".agents/skills").path) #expect( - AgentRegistry.usesCanonicalSkillsDirectory( + !AgentRegistry.usesCanonicalSkillsDirectory( for: .codex, scope: .user, environment: environment)) + #expect( + AgentRegistry.installSkillsDirectory(for: .codex, scope: .user, environment: environment).path + == codexHome.appendingPathComponent("skills").path) + #expect( + AgentRegistry.nativeUserScanDirectories(for: .antigravity, environment: environment).map( + \.path) + == [ + home.appendingPathComponent(".gemini/config/skills").path, + home.appendingPathComponent(".agents/skills").path, + ]) #expect( AgentRegistry.usesCanonicalSkillsDirectory( for: .cursor, scope: .user, environment: environment)) diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index 512b94c..d37cf7d 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -916,3 +916,74 @@ extension StateTransactionTests { #expect(outcome.terminal == .rolledBack && !outcome.recoveryPending) } } + +extension StateTransactionTests { + @Test func interruptedLegacyCodexJournalStillRecoversInTheSharedRoot() throws { + let fixture = try TransactionFixture() + var environment = fixture.store.environment + environment.environment["CODEX_HOME"] = + fixture.root.appendingPathComponent("codex-override").path + let store = StateStore(scope: .user, environment: environment) + let legacy = try store.skillInstallationTarget(for: .codex, named: "demo", root: "skills-codex") + let privateSkill = try store.skillInstallationTarget(for: .codex, named: "demo") + for (target, content) in [(legacy, "legacy-original"), (privateSkill, "unmanaged-private")] { + try FileManager.default.createDirectory(at: target.url, withIntermediateDirectories: true) + try Data(content.utf8).write(to: target.url.appendingPathComponent("SKILL.md")) + } + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "legacy-codex-publication", TransactionCheckpoint.publication(0, .exchanged).name, + "--scope", "user", + ]) + defer { terminateProcess(child) } + let marker = fixture.root.appendingPathComponent("ready") + try ProcessWait.marker(marker, child: child, root: fixture.root) + try ProcessWait.stopped(child, root: fixture.root) + let journal = store.directory.appendingPathComponent("transaction.json") + #expect(try String(contentsOf: journal, encoding: .utf8).contains("codex/demo")) + terminateProcess(child) + #expect(throws: CoreError.recoveryPending(TransactionRecoveryDiagnostic.pendingMessage)) { + try store.loadLedger() + } + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { + try store.withLock {} + } + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path)) + #expect( + try String(contentsOf: legacy.url.appendingPathComponent("SKILL.md"), encoding: .utf8) + == "legacy-original") + #expect( + try String(contentsOf: privateSkill.url.appendingPathComponent("SKILL.md"), encoding: .utf8) + == "unmanaged-private") + } +} + +extension StateTransactionTests { + @Test func hostTogglePublicationPreservesAConcurrentCodexSettingsWriter() throws { + let fixture = try TransactionFixture() + let store = fixture.store + let config = store.environment.projectDirectory.appendingPathComponent(".codex/config.toml") + try FileManager.default.createDirectory( + at: config.deletingLastPathComponent(), withIntermediateDirectories: true) + let original = Data("model = 'first'\n".utf8) + let concurrent = Data("model = 'new'\n".utf8) + let toggle = Data("[plugins.'test@local']\nenabled = false\n".utf8) + try original.write(to: config) + #expect(throws: CoreError.self) { + try HostPluginConfigurationRoute.codex.edit(store: store, maximumFileBytes: 4096) { before in + #expect(before == original) + try concurrent.write(to: config, options: .atomic) + return original + toggle + } + } + #expect(try Data(contentsOf: config) == concurrent) + try HostPluginConfigurationRoute.codex.edit(store: store, maximumFileBytes: 4096) { before in + #expect(before == concurrent) + return concurrent + toggle + } + #expect(try Data(contentsOf: config) == concurrent + toggle) + } +} diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift index 7e48c7c..c21b512 100644 --- a/Tests/AgentsCoreTests/TransactionCostTests.swift +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -93,7 +93,7 @@ struct TransactionCostTests { #expect(try Data(contentsOf: target.url.appendingPathComponent("SKILL.md")) == bytes) let expected = target.agent == .claudeCode - ? physical.appendingPathComponent("skills") : home.appendingPathComponent(".agents/skills") + ? physical.appendingPathComponent("skills") : home.appendingPathComponent(".codex/skills") #expect(target.url.deletingLastPathComponent().path == expected.path) } #expect( diff --git a/Tests/AgentsManifestTests/FullDeclarationTests.swift b/Tests/AgentsManifestTests/FullDeclarationTests.swift index 9af45c9..c6e6750 100644 --- a/Tests/AgentsManifestTests/FullDeclarationTests.swift +++ b/Tests/AgentsManifestTests/FullDeclarationTests.swift @@ -552,3 +552,47 @@ struct FullDeclarationTests { try planned(declaration, declaration, in: String(decoding: bytes, as: UTF8.self)) == nil) } } + +extension FullDeclarationTests { + @Test func hostPluginSelectorsRoundTripAndRequireAuthoredRecipients() throws { + let input = """ + version: 1 + defaultAgents: [codex] + sources: {pack: {path: ./plugins}} + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} + - {kind: hostPlugin, name: local, source: pack, path: local, agents: [claude-code, antigravity], enabled: false, claudeScope: local} + """ + let declaration = try projected(input) + #expect( + declaration.components == [ + .hostPlugin( + .init( + name: "github", selector: .marketplace(pluginId: "github@curated"), agents: [.codex])), + .hostPlugin( + .init( + name: "local", selector: .bundle(source: "pack", path: "local"), + agents: [.claudeCode, .antigravity], enabled: false, claudeScope: .local)), + ]) + let bytes = try #require(try planned(Declaration(), declaration, in: "version: 1\n")) + #expect(try projected(String(decoding: bytes, as: UTF8.self)) == declaration) + + for fields in [ + "pluginId: x@y", + "pluginId: x@y, agents: []", + "pluginId: x@y, agents: [codex, claude-code]", + "source: pack, path: x, agents: []", + "pluginId: x@y, source: pack, path: x, agents: [codex]", + "pluginId: x@y, agents: [codex], enabled: 'true'", + "source: pack, agents: [codex]", + ] { + let invalid = """ + version: 1 + defaultAgents: [codex] + sources: {pack: {path: ./plugins}} + components: [{kind: hostPlugin, name: x, \(fields)}] + """ + #expect(throws: ManifestFailure.self) { try projected(invalid) } + } + } +} diff --git a/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift b/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift new file mode 100644 index 0000000..b3efef3 --- /dev/null +++ b/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift @@ -0,0 +1,141 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Codex user skill isolation") +struct CodexUserIsolationTests { + @Test(arguments: [false, true]) + func migratesVerifiedLegacyDeploymentDuringUpdateOrRestore(_ restore: Bool) throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "locked") + try fixture.commit() + _ = try fixture.add(mode: .copy, scope: .user) + let (privateSkill, sharedSkill) = try seedLegacy(fixture) + let store = fixture.store(.user) + #expect(try store.loadResolved().skills["demo"]?.installs["codex"] == .copy) + #expect(try store.loadLedger().deployments.first?.target.root == "skills-codex") + + if restore { + _ = try UpdateOperations.restore( + scope: .user, environment: fixture.environment, offline: true) + } else { + _ = try SkillOperations.updateInstalled( + scope: .user, environment: fixture.environment, apply: true) + } + + #expect(try fixture.body(privateSkill).contains("locked")) + #expect(!FileManager.default.fileExists(atPath: sharedSkill.path)) + #expect(try store.loadLedger().deployments.first?.target.root == "skills-codex-private") + } + + @Test(arguments: [false, true]) + func rejectsOccupiedPrivateDestinationWithoutTransferringOwnership(_ dangling: Bool) throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "owned") + try fixture.commit() + _ = try fixture.add(mode: .copy, scope: .user) + let (privateSkill, sharedSkill) = try seedLegacy(fixture) + if dangling { + try FileManager.default.createSymbolicLink( + atPath: privateSkill.path, withDestinationPath: "unrelated-missing-target") + } else { + try FileManager.default.createDirectory(at: privateSkill, withIntermediateDirectories: true) + try Data("unmanaged".utf8).write(to: privateSkill.appendingPathComponent("SKILL.md")) + } + let store = fixture.store(.user) + let before = try Data(contentsOf: store.resolvedURL) + #expect(throws: (any Error).self) { + try UpdateOperations.restore(scope: .user, environment: fixture.environment, offline: true) + } + #expect(try Data(contentsOf: store.resolvedURL) == before) + #expect(try fixture.body(sharedSkill).contains("owned")) + if dangling { + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: privateSkill.path) + == "unrelated-missing-target") + } else { + #expect(try fixture.body(privateSkill) == "unmanaged") + } + } + + @Test func migrationKeepsCursorOwnedSharedLeafAndWarnsOnlyAboutUnmanagedLinks() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "shared") + try fixture.commit() + _ = try SkillOperations.add( + AddOptions( + source: fixture.repo.path, agents: [.codex, .cursor], scope: .user, mode: .copy, all: true, + environment: fixture.environment)) + let (privateSkill, sharedSkill) = try seedLegacy(fixture) + let sharedBefore = try fixture.body(sharedSkill) + _ = try UpdateOperations.restore(scope: .user, environment: fixture.environment, offline: true) + + #expect(try fixture.body(sharedSkill) == sharedBefore) + #expect(try fixture.body(privateSkill) == sharedBefore) + let first = try SkillGovernance.inspect( + scope: .user, agents: [.codex], environment: fixture.environment) + #expect(first.checks.allSatisfy { $0.id != "codex-legacy-skill-link" }) + + try SkillOperations.remove( + skillNames: ["demo"], scope: .user, agents: [.cursor], environment: fixture.environment) + try FileManager.default.createSymbolicLink( + atPath: sharedSkill.path, withDestinationPath: privateSkill.path) + let second = try SkillGovernance.inspect( + scope: .user, agents: [.codex], environment: fixture.environment) + #expect(second.checks.filter { $0.id == "codex-legacy-skill-link" }.count == 1) + #expect( + try SkillGovernance.inspect( + scope: .user, agents: [.cursor], environment: fixture.environment + ).checks.allSatisfy { $0.id != "codex-legacy-skill-link" }) + } + + @Test func installsUnderExplicitCodexHomeWhileAntigravityScansSharedHome() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "local") + var environment = fixture.environment + let override = fixture.root.appendingPathComponent("codex-override") + environment.environment["CODEX_HOME"] = override.path + _ = try SkillOperations.add( + AddOptions( + source: fixture.repo.path, agents: [.codex], scope: .user, mode: .edit, all: true, + environment: environment)) + let privateSkill = override.appendingPathComponent("skills/demo") + #expect(try fixture.body(privateSkill).contains("local")) + #expect( + try SkillOperations.listInstalled( + scope: .user, agents: [.antigravity], environment: environment + ).isEmpty) + let sharedSkill = environment.homeDirectory.appendingPathComponent(".agents/skills/demo") + try FileManager.default.createDirectory( + at: sharedSkill.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: sharedSkill.path, withDestinationPath: privateSkill.path) + #expect( + try SkillOperations.listInstalled( + scope: .user, agents: [.antigravity], environment: environment + ).map(\.name) == ["demo"]) + } + + private func seedLegacy(_ fixture: SkillFixture) throws -> (URL, URL) { + let privateSkill = fixture.target("demo", scope: .user) + let sharedSkill = fixture.environment.homeDirectory.appendingPathComponent( + ".agents/skills/demo") + try FileManager.default.createDirectory( + at: sharedSkill.deletingLastPathComponent(), withIntermediateDirectories: true) + if FileManager.default.fileExists(atPath: sharedSkill.path) { + try FileManager.default.removeItem(at: privateSkill) + } else { + try FileManager.default.moveItem(at: privateSkill, to: sharedSkill) + } + let store = fixture.store(.user) + var ledger = try store.loadLedger() + let index = try #require(ledger.deployments.firstIndex { $0.recipients == [.codex] }) + ledger.deployments[index].target.root = "skills-codex" + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) + return (privateSkill, sharedSkill) + } +} diff --git a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift index 5364698..e871adf 100644 --- a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift +++ b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift @@ -197,3 +197,24 @@ private func writeDiscoverySkill(_ directory: URL, name: String) throws { --- """.write(to: directory.appendingPathComponent("SKILL.md"), atomically: true, encoding: .utf8) } + +extension SkillDiscoveryTests { + @Test func discoversLocalMarketplaceObjectsAlongsideOrdinarySkills() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let marketplace = root.appendingPathComponent(".agents/plugins/marketplace.json") + try FileManager.default.createDirectory( + at: marketplace.deletingLastPathComponent(), withIntermediateDirectories: true) + try """ + {"name":"local","plugins":[ + {"name":"review","source":{"source":"local","path":"./plugins/review"}, + "skills":["./extras/technical"]}]} + """.write(to: marketplace, atomically: true, encoding: .utf8) + try writeDiscoverySkill( + root.appendingPathComponent("plugins/review/extras/technical"), name: "technical-review") + try writeDiscoverySkill(root.appendingPathComponent("skills/ordinary"), name: "ordinary") + let skills = try Discovery.discover(in: root) + #expect(skills.map(\.name).sorted() == ["ordinary", "technical-review"]) + #expect(skills.first { $0.name == "technical-review" }?.pluginName == "review") + } +} diff --git a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift index aed4e65..4a1025c 100644 --- a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift +++ b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift @@ -16,7 +16,7 @@ struct InstalledInventoryTests { fixture.root.appendingPathComponent("configured-codex").path environment.environment["XDG_CONFIG_HOME"] = fixture.root.appendingPathComponent("configured-xdg").path - let universal = fixture.target("unused", scope: scope).deletingLastPathComponent() + let universal = AgentRegistry.canonicalSkillsDirectory(scope: scope, environment: environment) try FileManager.default.createDirectory(at: universal, withIntermediateDirectories: true) let live = try SkillOperations.initializeSkill( named: "linked", directory: fixture.root.appendingPathComponent("live")) @@ -60,6 +60,10 @@ struct InstalledInventoryTests { scope: scope, agents: [.opencode], environment: environment ).map(\.name)) == ["opencode-native", "linked"]) } + #expect( + try SkillOperations.listInstalled( + scope: scope, agents: [.antigravity], environment: environment + ).map(\.name) == ["linked"]) let codex = try SkillOperations.listInstalled( scope: scope, agents: [.codex], environment: environment) #expect(Set(codex.map(\.name)) == expectedCodex) diff --git a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift index 8f28cae..c56570c 100644 --- a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift @@ -155,23 +155,30 @@ struct RetainedLifecycleTests { source: fixture.repo.path, agents: AgentRegistry.skillAgents, scope: .user, environment: environment) ) - let shared = fixture.target("demo", scope: .user) + let shared = AgentRegistry.canonicalSkillsDirectory(scope: .user, environment: environment) + .appendingPathComponent("demo") + let codex = fixture.target("demo", scope: .user) let claude = claudeRoot.appendingPathComponent("skills/demo") let antigravity = environment.homeDirectory.appendingPathComponent(".gemini/config/skills/demo") #expect(try fixture.body(shared).contains("A")) + #expect(try fixture.body(codex).contains("A")) #expect(try fixture.body(claude).contains("A")) #expect(try fixture.body(antigravity).contains("A")) #expect( !(try FileManager.default.destinationOfSymbolicLink(atPath: shared.path)).hasPrefix("/")) let bytes = try Data(contentsOf: fixture.store(.user).resolvedURL) - for target in [shared, claude, antigravity] { try FileManager.default.removeItem(at: target) } + for target in [shared, codex, claude, antigravity] { + try FileManager.default.removeItem(at: target) + } _ = try SkillOperations.installResolvedReport(scope: .user, environment: environment) #expect(try Data(contentsOf: fixture.store(.user).resolvedURL) == bytes) #expect(try fixture.body(shared).contains("A")) + #expect(try fixture.body(codex).contains("A")) #expect(try fixture.body(claude).contains("A")) #expect(try fixture.body(antigravity).contains("A")) _ = try SkillOperations.remove( skillNames: ["demo"], scope: .user, agents: [.codex], environment: environment) + #expect(!FileManager.default.fileExists(atPath: codex.path)) #expect(FileManager.default.fileExists(atPath: shared.path)) #expect(try fixture.store(.user).loadResolved().skills["demo"]?.installs.count == 5) _ = try SkillOperations.remove( diff --git a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift index 997b23d..8df63b9 100644 --- a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift @@ -345,8 +345,9 @@ final class SkillFixture { environment: environment)) } func target(_ name: String, scope: InstallScope = .project) -> URL { - (scope == .project ? environment.projectDirectory : environment.homeDirectory) - .appendingPathComponent(".agents/skills/\(name)") + AgentRegistry.installSkillsDirectory( + for: .codex, scope: scope, environment: environment + ).appendingPathComponent(name) } func body(_ target: URL) throws -> String { try String(contentsOf: target.appendingPathComponent("SKILL.md"), encoding: .utf8) diff --git a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift new file mode 100644 index 0000000..59212c4 --- /dev/null +++ b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift @@ -0,0 +1,314 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Host plugin execution") +struct HostPluginExecutorTests { + @Test func dryRunAndOrdinaryUpdateDoNotInvokeOrWriteHostState() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + sources: {pack: {path: ./pack}} + components: + - {kind: hostPlugin, name: review, source: pack, path: review, agents: [codex, claude-code, antigravity]} + """) + try fixture.write( + #"{"name":"work","plugins":[{"name":"review","source":{"source":"local","path":"./review"}}]}"#, + at: fixture.project.appendingPathComponent("pack/.agents/plugins/marketplace.json")) + try fixture.write( + #"{"name":"work","plugins":[{"name":"review","source":"./review"}]}"#, + at: fixture.project.appendingPathComponent("pack/.claude-plugin/marketplace.json")) + let pack = fixture.project.appendingPathComponent("pack/review") + try fixture.write(#"{"name":"review"}"#, at: pack.appendingPathComponent("plugin.json")) + let runner = RecordingHostRunner { _, _ in .failed } + let before = try FileHash.folderHash(fixture.root) + let preview = try await HostPluginExecutor.sync( + environment: fixture.environment, runner: runner) + #expect(preview.allSatisfy { $0.outcome == nil }) + #expect(preview.map(\.status.agent) == [.codex, .claudeCode, .antigravity]) + #expect( + preview[0].preview.commands == [ + [ + "codex", "plugin", "marketplace", "add", + fixture.project.appendingPathComponent("pack").path, + ], + ["codex", "plugin", "add", "review@work", "--json"], + ]) + #expect( + preview[1].preview.commands.last == [ + "claude", "plugin", "enable", "review@work", "--scope", "project", + ]) + #expect(preview[2].preview.commands.isEmpty) + #expect(preview[2].preview.configurationChanges.first?.after == .appendPath("pack/review")) + #expect(await runner.calls.isEmpty) + #expect( + try HostPluginExecutor.preview( + agents: [.codex], environment: fixture.environment + ).count == 1) + #expect(try FileHash.folderHash(fixture.root) == before) + + _ = try UpdateOperations.preview(environment: fixture.environment) + #expect(try FileHash.folderHash(fixture.root) == before) + let ledger = try UpdateOperations.restore(environment: fixture.environment, offline: true) + #expect(ledger.report.components.isEmpty) + #expect(try FileManager.default.contentsOfDirectory(atPath: fixture.home.path).isEmpty) + #expect( + !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent(".codex").path) + ) + } + + @Test func codexInstallReadbackPreservesUnrelatedSettingsAndThenTogglesOffline() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, enabled: false, agents: [codex]} + """, scope: .user) + let config = fixture.home.appendingPathComponent(".codex/config.toml") + let runner = RecordingHostRunner { argv, environment in + #expect(environment.homeDirectory == fixture.home) + guard argv == ["codex", "plugin", "add", "github@curated", "--json"] else { return .failed } + do { + try fixture.write( + #""" + # The host writes unrelated settings at the same time it installs a plugin. + model = "new-model" + [plugins."github@curated"] + enabled = true + [mcp_servers.unrelated] + command = "keep" + """# + "\n", at: config) + try fixture.codexBundle("curated/github/1") + return .success + } catch { return .failed } + } + let installed = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(installed.first?.outcome == .installed) + #expect(installed.first?.status.installed == true) + #expect(installed.first?.status.explicitEnabled == false) + #expect(installed.first?.status.effectiveEnabled == false) + let output = try String(contentsOf: config, encoding: .utf8) + #expect(output.contains("enabled = false")) + #expect(output.contains("model = \"new-model\"") && output.contains("command = \"keep\"")) + #expect(output.contains("# The host writes unrelated settings")) + + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} + """, scope: .user) + let changed = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(changed.first?.preview.status.drift == .enablement) + #expect(changed.first?.outcome == .enabled) + #expect(changed.first?.commandsRun == []) + #expect(await runner.calls.count == 1) + let repeated = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(repeated.first?.outcome == .unchanged) + } + + @Test func timeoutIsReconciledAndCliFailuresAreIndependent() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: codex, pluginId: github@curated, agents: [codex]} + - {kind: hostPlugin, name: claude, pluginId: review@work, agents: [claude-code], claudeScope: local} + - {kind: hostPlugin, name: agy, pluginId: notes, agents: [antigravity]} + """, scope: .user) + let runner = RecordingHostRunner { argv, _ in + switch argv.first { + case "codex": + do { + try fixture.codexBundle("curated/github/1") + try fixture.write( + """ + [plugins."github@curated"] + enabled = true + """, at: fixture.home.appendingPathComponent(".codex/config.toml")) + return .timeout + } catch { return .failed } + case "claude": + #expect(argv == ["claude", "plugin", "install", "review@work", "--scope", "local"]) + return .authRequired + case "agy": return .cliUnavailable + default: return .failed + } + } + let result = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(result.map(\.outcome) == [.timeout, .authRequired, .cliUnavailable]) + #expect(result[0].status.installed == true) + #expect(result[0].status.effectiveEnabled == true) + #expect(result[0].status.drift == .current) + #expect(result[1].status.drift == .missing) + #expect(result.allSatisfy { $0.commandsRun.count == 1 }) + } + + @Test func antigravityProjectRegistrationPreservesEntriesAndCannotOverrideGlobalDisable() + async throws + { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: project, source: ".", path: bundles/project, agents: [antigravity]} + - {kind: hostPlugin, name: blocked, pluginId: blocked, agents: [antigravity]} + """) + try fixture.write( + #"{"name":"namespace"}"#, + at: fixture.project.appendingPathComponent("bundles/project/plugin.json")) + try fixture.write( + #"{"name":"different-name"}"#, + at: fixture.home.appendingPathComponent(".gemini/config/plugins/blocked/plugin.json")) + try fixture.write( + #"{"plugins":{"blocked":{"enabled":false},"different-name":{"enabled":true}}}"#, + at: fixture.home.appendingPathComponent(".gemini/config/config.json")) + let discovery = fixture.project.appendingPathComponent(".agents/plugins.json") + try fixture.write(#"{"entries":[{"path":"existing"}],"exclude":["some-other"]}"#, at: discovery) + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + #expect(result.map(\.outcome) == [.installed, .unsupported]) + #expect(result[0].status.effectiveEnabled == true) + #expect(result[1].status.effectiveEnabled == false) + #expect(await runner.calls.isEmpty) + let json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: discovery)) as? [String: Any]) + #expect( + (json["entries"] as? [[String: String]])?.compactMap { $0["path"] } + == ["existing", "bundles/project"]) + #expect(json["exclude"] as? [String] == ["some-other"]) + } + + @Test func antigravityUserUsesDirectoryIdentityAndValidatesBeforeInstall() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + sources: {pack: {path: ./pack}} + components: + - {kind: hostPlugin, name: local, source: pack, path: bundle, agents: [antigravity], enabled: false} + """, scope: .user) + let local = fixture.project.appendingPathComponent("pack/bundle") + try fixture.write(#"{"name":"display-name"}"#, at: local.appendingPathComponent("plugin.json")) + let runner = RecordingHostRunner { argv, _ in + do { + switch argv { + case ["agy", "plugin", "validate", local.path]: return .success + case ["agy", "plugin", "install", local.path]: + try fixture.write( + #"{"name":"display-name"}"#, + at: fixture.home.appendingPathComponent(".gemini/config/plugins/bundle/plugin.json")) + return .success + case ["agy", "plugin", "disable", "bundle"]: + try fixture.write( + #"{"plugins":{"bundle":{"enabled":false}}}"#, + at: fixture.home.appendingPathComponent(".gemini/config/config.json")) + return .success + default: return .failed + } + } catch { return .failed } + } + let result = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(result.first?.outcome == .installed) + #expect(result.first?.status.explicitEnabled == false) + #expect(result.first?.commandsRun.map { $0[2] } == ["validate", "install", "disable"]) + } + + @Test func processRunnerClosesInputClassifiesAuthenticationAndBoundsTimeout() async throws { + let fixture = try HostPluginFixture() + let command = fixture.root.appendingPathComponent("mock-host") + try fixture.write( + """ + #!/bin/sh + test "$HOME" = "$1" || exit 2 + if read -r line; then exit 3; fi + if test "$2" = auth; then + echo 'Authentication required' >&2 + exit 1 + fi + if test "$2" = sleep; then /bin/sleep 30; fi + """, at: command) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: command.path) + var environment = fixture.environment + environment.environment["PATH"] = fixture.root.path + let runner = ProcessHostPluginCommandRunner(timeout: .seconds(15)) + let shortTimeout = ProcessHostPluginCommandRunner(timeout: .seconds(1)) + #expect( + await runner.run(argv: ["mock-host", fixture.home.path, "ok"], environment: environment) + == .success) + #expect( + await runner.run(argv: ["mock-host", fixture.home.path, "auth"], environment: environment) + == .authRequired) + #expect( + await shortTimeout.run( + argv: ["mock-host", fixture.home.path, "sleep"], environment: environment) == .timeout) + #expect(await runner.run(argv: ["absent-host"], environment: environment) == .cliUnavailable) + } +} + +actor RecordingHostRunner: HostPluginCommandRunner { + private(set) var calls: [[String]] = [] + let action: @Sendable ([String], RuntimeEnvironment) -> HostPluginCommandResult + + init(_ action: @escaping @Sendable ([String], RuntimeEnvironment) -> HostPluginCommandResult) { + self.action = action + } + + func run(argv: [String], environment: RuntimeEnvironment) async -> HostPluginCommandResult { + calls.append(argv) + return action(argv, environment) + } +} + +final class HostPluginFixture: Sendable { + let root: URL + let environment: RuntimeEnvironment + var home: URL { environment.homeDirectory } + var project: URL { environment.projectDirectory } + + init(variables: [String: String] = [:]) throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "host-plugin-tests-" + UUID().uuidString) + environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), environment: variables) + for directory in [environment.homeDirectory, environment.projectDirectory] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + } + + deinit { try? FileManager.default.removeItem(at: root) } + + func write(_ text: String, at url: URL) throws { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: url) + } + + func declare(_ text: String, scope: InstallScope = .project) throws { + let store = StateStore(scope: scope, environment: environment) + try write("version: 1\n" + text, at: store.declarationURL) + } + + func codexBundle(_ path: String) throws { + try write( + #"{"name":"github"}"#, + at: home.appendingPathComponent(".codex/plugins/cache/" + path + "/.codex-plugin/plugin.json") + ) + } + + func skill( + path: URL, name: String, description: String, extra: String = "" + ) throws { + try write( + "---\nname: '\(name)'\ndescription: '\(description)'\n\(extra)---\n\nBody\n", + at: path.appendingPathComponent("SKILL.md")) + } +} diff --git a/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift b/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift new file mode 100644 index 0000000..a38ccfd --- /dev/null +++ b/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift @@ -0,0 +1,130 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +@Suite("Deterministic skill governance") +struct SkillGovernanceTests { + @Test func comparesParsedNamesAndPhysicalFilesAgainstDefaultEnabledPlugins() throws { + let fixture = try HostPluginFixture() + let plugin = fixture.home.appendingPathComponent(".gemini/config/plugins/wrong-directory") + try fixture.write(#"{"name":"pdf"}"#, at: plugin.appendingPathComponent("plugin.json")) + let pluginSkill = plugin.appendingPathComponent("skills/different-leaf") + try fixture.skill(path: pluginSkill, name: "review", description: "PDF") + try fixture.skill( + path: fixture.project.appendingPathComponent(".agents/skills/one"), name: "review", + description: "Standalone") + try fixture.skill( + path: fixture.home.appendingPathComponent(".agents/skills/two"), name: "pdf:review", + description: "Shared") + let aliased = fixture.project.appendingPathComponent(".agents/skills/alias") + try FileManager.default.createSymbolicLink(at: aliased, withDestinationURL: pluginSkill) + let before = try FileHash.folderHash(fixture.root) + let full = try SkillGovernance.inspect( + agents: [.antigravity], environment: fixture.environment) + #expect(full.checks.filter { $0.collision == .basenameOverlap }.count == 2) + #expect(full.checks.filter { $0.collision == .divergentTarget }.count == 1) + #expect(full.checks.allSatisfy { $0.agent == .antigravity && $0.status == .warning }) + #expect(full.skillBudgets?.first?.skills == 2) + #expect( + try SkillGovernance.inspect(agents: [.antigravity], environment: fixture.environment) == full) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect( + try SkillGovernance.inspect(agents: [.codex], environment: fixture.environment) + .checks.allSatisfy { $0.collision == nil }) + } + + @Test func codexReadbackClassifiesRealpathAliasesAndDivergentCollisions() throws { + let fixture = try HostPluginFixture() + let plugin = fixture.home.appendingPathComponent(".codex/plugins/cache/curated/github/1") + try fixture.codexBundle("curated/github/1") + let pluginSkill = plugin.appendingPathComponent("skills/vendor-file") + try fixture.skill(path: pluginSkill, name: "shared", description: "Plugin") + let config = fixture.home.appendingPathComponent(".codex/config.toml") + try fixture.write(#"[plugins."github@curated"]"# + "\n", at: config) + let project = fixture.project.appendingPathComponent(".agents/skills") + let user = fixture.home.appendingPathComponent(".codex/skills") + try fixture.skill( + path: project.appendingPathComponent("local-different"), name: "shared", + description: "Project winner") + try FileManager.default.createSymbolicLink( + at: project.appendingPathComponent("local-same"), + withDestinationURL: pluginSkill) + try FileManager.default.createSymbolicLink(at: user, withDestinationURL: project) + let report = try SkillGovernance.inspect(agents: [.codex], environment: fixture.environment) + #expect(report.checks.compactMap(\.collision) == [.divergentTarget, .sameTarget]) + #expect(report.skillBudgets?.first?.utf8Bytes == ("shared" + "Project winner").utf8.count) + #expect(report.skillBudgets?.first?.skills == 1) + + try fixture.write(#"[plugins."github@curated"]"# + "\nenabled = false\n", at: config) + #expect( + try SkillGovernance.inspect(agents: [.codex], environment: fixture.environment).checks.isEmpty + ) + } + + @Test func claudeScopePrecedenceAndBudgetSkipInternalSkillsAndOpaqueSelfCollision() throws { + let fixture = try HostPluginFixture(variables: ["SLASH_COMMAND_TOOL_CHAR_BUDGET": "12"]) + let claude = fixture.home.appendingPathComponent(".claude") + let local = fixture.project.appendingPathComponent(".claude") + let plugin = claude.appendingPathComponent("plugins/cache/work/vendor/1") + try fixture.skill( + path: plugin.appendingPathComponent("skills/vendor-name"), name: "vendor", + description: "Vendé") + try fixture.write( + """ + {"plugins":{"vendor@work":[{"scope":"user","installPath":"\(plugin.path)"}]}} + """, at: claude.appendingPathComponent("plugins/installed_plugins.json")) + try fixture.write( + #"{"enabledPlugins":{"vendor@work":false}}"#, + at: claude.appendingPathComponent("settings.json")) + try fixture.write( + #"{"enabledPlugins":{"vendor@work":true}}"#, + at: local.appendingPathComponent("settings.local.json")) + let opaque = local.appendingPathComponent("skills/generated") + try fixture.write( + #"{"name":"generated"}"#, at: opaque.appendingPathComponent(".claude-plugin/plugin.json")) + try fixture.skill(path: opaque, name: "both", description: "Root") + try fixture.skill( + path: opaque.appendingPathComponent("skills/another-name"), name: "both", + description: "Child") + try fixture.skill( + path: local.appendingPathComponent("skills/internal"), name: "private", + description: "Excluded", extra: "metadata: {internal: true}\n") + + let report = try SkillGovernance.inspect( + agents: [.claudeCode], environment: fixture.environment) + #expect(report.checks.compactMap(\.collision).isEmpty) + #expect(report.checks.map(\.id) == ["skill-listing-budget"]) + let budget = try #require(report.skillBudgets?.first) + #expect(budget.skills == 2) + #expect(budget.advisoryThreshold == 12) + #expect(budget.utf8Bytes == ("both" + "Root" + "vendor" + "Vendé").utf8.count) + #expect(budget.estimate.contains("Estimated")) + } + + @Test func unverifiedReadbackDoesNotInventAnEffectivePluginState() throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} + """) + try fixture.write( + "[bad config", at: fixture.project.appendingPathComponent(".codex/config.toml")) + let report = try SkillGovernance.inspect(agents: [.codex], environment: fixture.environment) + #expect(report.hostPlugins.first?.drift == .unverified) + #expect(report.hostPlugins.first?.effectiveEnabled == nil) + #expect(report.hostPlugins.first?.installed == nil) + #expect(report.checks.map(\.id) == ["host-plugin-unverified"]) + #expect(report.skillBudgets == nil) + } + + @Test func emptyScopesOmitBudgetFromCodableGovernanceReport() throws { + let fixture = try HostPluginFixture() + let report = try SkillGovernance.inspect(environment: fixture.environment) + #expect(report.checks.isEmpty) + #expect(!report.recoveryPending) + #expect( + !String(decoding: try JSONEncoder().encode(report), as: UTF8.self).contains("skillBudgets")) + } +} diff --git a/Tests/ComponentsTests/SourceCatalogTests.swift b/Tests/ComponentsTests/SourceCatalogTests.swift index 58f282e..4ad32b0 100644 --- a/Tests/ComponentsTests/SourceCatalogTests.swift +++ b/Tests/ComponentsTests/SourceCatalogTests.swift @@ -251,3 +251,80 @@ struct SourceCatalogTests { } } + +extension SourceCatalogTests { + @Test func portableManifestRecordsItsOwnAdapterAndMetadata() throws { + let fixture = try LinkFixture() + try fixture.write( + """ + {"$schema":"\(AgentPluginManifest.schema)","name":"portable","version":"1.2.3", + "description":"One skill","author":{"name":"Example"},"keywords":["review"]} + """, to: "bundle/plugin.json", base: fixture.project) + try fixture.write( + "---\nname: review\ndescription: Review skill\n---\nBody\n", + to: "bundle/skills/review/SKILL.md", base: fixture.project) + let catalog = try inspect(fixture, path: "bundle") + let components = catalog.choices.filter { + if case .componentsPlugin = $0.unit { true } else { false } + } + #expect(components.count == 1) + let entry = try #require(components.first) + #expect(entry.origin.document == "bundle/plugin.json") + #expect(entry.graph?.components.filter { $0.key.kind == .skills }.count == 1) + #expect( + entry.graph?.components.first?.origins.first?.pluginExpansion?.input.format + == "native/agentPluginV1@1") + + let proposal = try SourceImport.preview( + .init( + profile: .agentPluginV1, root: fixture.project, document: "bundle/plugin.json")) + #expect(proposal.packageMetadata?.name == "portable") + #expect(proposal.packageMetadata?.version == "1.2.3") + #expect(proposal.packageMetadata?.description == "One skill") + #expect(proposal.packageMetadata?.author == ["name": "Example"]) + #expect(proposal.packageMetadata?.keywords == ["review"]) + } + + @Test func arbitraryRootPluginJSONDoesNotProduceAPluginChoice() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"not-portable"}"#, to: "bundle/plugin.json", base: fixture.project) + let catalog = try inspect(fixture, path: "bundle") + #expect(catalog.choices.isEmpty) + #expect(throws: LinkError.self) { + try fixture.link( + """ + version: 1 + components: [{kind: plugin, name: test, path: bundle, source: "."}] + """) + } + } + + @Test(arguments: ["same", nil, "different"] as [String?]) + func coalescesMatchingDualManifestsAndRejectsConflictingNames(_ portableName: String?) throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"same"}"#, to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let name = portableName.map { #","name":"\#($0)""# } ?? "" + try fixture.write( + #"{"$schema":"\#(AgentPluginManifest.schema)"\#(name)}"#, + to: "bundle/plugin.json", base: fixture.project) + let expression = """ + version: 1 + components: [{kind: plugin, name: test, path: bundle, source: ".", agents: [claude-code]}] + """ + if portableName == "different" { + #expect(throws: (any Error).self) { try inspect(fixture, path: "bundle") } + #expect(throws: (any Error).self) { try fixture.link(expression) } + } else { + let catalog = try inspect(fixture, path: "bundle") + #expect(catalog.choices.count == 2) + #expect( + catalog.choices.allSatisfy { $0.origin.document == "bundle/.claude-plugin/plugin.json" }) + let graph = try fixture.link(expression) + let expansion = graph.components.first?.origins.first?.pluginExpansion + #expect(expansion?.input.format == "native/claudePluginV1@1") + #expect(expansion?.document == "bundle/.claude-plugin/plugin.json") + } + } +} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 77e57e4..063898f 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -264,6 +264,16 @@ if arguments[2].hasPrefix("acquisition-") { } else if arguments[2] == "watch-recover" { do { try store.withLock(checkpoint: { try stop($0) }, {}) } catch CoreError.transactionRecovered { } +} else if arguments[2] == "legacy-codex-publication" { + var environment = store.environment + environment.environment["CODEX_HOME"] = root.appendingPathComponent("codex-override").path + let user = StateStore(scope: .user, environment: environment) + let legacy = try user.skillInstallationTarget(for: .codex, named: "demo", root: "skills-codex") + try user.withLock(installations: [legacy]) { + let transaction = FileTransaction(store: user, checkpoint: { try stop($0) }) + try transaction.replaceSkill(legacy, with: .copy(root.appendingPathComponent("new"))) + try transaction.commit() + } } else if arguments[2] == "publication-recover" { let outcome = TransactionOutcome() let result: String From 8afd49d167aa3a8fdad33c9c8c27cc662872638a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:08:38 +0800 Subject: [PATCH 02/10] fix: resolve host plugin safety, migration isolation and governance review findings --- CHANGELOG.md | 6 +- Documentation/Architecture/Package.md | 24 +- Documentation/Reference/ManifestSchema.md | 4 +- Scripts/generate-manifest-schema.py | 17 +- Scripts/test_manifest_schema.py | 18 + .../AgentsCore/HostPluginConfiguration.swift | 119 +++--- .../AgentsCore/NativeTargetCoordination.swift | 7 +- .../AgentsCore/PrivateMaterialization.swift | 11 + Sources/AgentsManifest/ManifestSchema.swift | 4 +- .../Resources/agents.schema.json | 8 +- Sources/AgentsManifest/YAMLValidation.swift | 7 +- .../HostPlugins/HostPluginExecutor.swift | 129 +++++-- .../HostPlugins/HostPluginInventory.swift | 202 +++++++--- .../HostPlugins/HostPluginTarget.swift | 154 ++++++-- .../HostPlugins/SkillGovernance.swift | 5 +- Sources/AgentsUpdates/UpdatePlan.swift | 11 +- Sources/Components/ArtifactAggregation.swift | 21 +- .../Components/DeploymentConstruction.swift | 25 +- Sources/Components/Expansion.swift | 4 +- Sources/Components/Import/ImportInput.swift | 27 +- .../Import/NativeContainerImport.swift | 4 +- .../NativeGeneratedPluginLayoutV1.swift | 23 +- Sources/Components/PluginExpansion.swift | 17 +- .../StateTransactionTests.swift | 70 ++++ .../CodexUserIsolationTests.swift | 38 +- .../HostPluginExecutorTests.swift | 352 ++++++++++++++++++ .../PortablePluginDeploymentTests.swift | 34 ++ .../PrivateNativeCompositionTests.swift | 41 ++ .../SkillGovernanceTests.swift | 85 ++++- .../ComponentsTests/SourceCatalogTests.swift | 43 +++ Tests/StateTestProcess/main.swift | 6 + 31 files changed, 1274 insertions(+), 242 deletions(-) create mode 100644 Tests/AgentsUpdatesTests/PortablePluginDeploymentTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 742c693..92077e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,9 +31,9 @@ publication follows the [release checklist](Documentation/Reference/Release.md). - Route new user-scope Codex skill deployments to `$CODEX_HOME/skills` (`~/.codex/skills`) under a dedicated `skills-codex-private` ledger root while - preserving historical `skills-codex` ledger/journal semantics for safe - ownership-checked migration without taking over unmanaged private destinations - or removing shared leaves owned by other agents. + preserving historical ledger and journal paths. Selected deployments migrate + after ownership and destination checks. Unselected deployments retain their + recorded paths, and leaves shared with other agents retain their ownership. - Include `~/.agents/skills` in `AgentRegistry.nativeUserScanDirectories` for Antigravity. diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 277e4ad..703d5c0 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -448,7 +448,9 @@ keys retain the adapter's complete family effects, fixed contributions, requirem and separate producer selection claims. The Agent Plugins 1.0 manifest schema identifies a portable root `plugin.json`. When a bundle also has a Claude manifest, components mode uses the Claude document once and validates agreement -between the declared names. Captured content and paths remain source- +between the declared names. Portable skills inherit the plugin declaration’s +recipients and use standalone skill routes on hosts without a generated +container for the selected scope. 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. @@ -459,22 +461,28 @@ the package catalog does not create update requests. and NativeDocuments to observe host installations and report exact command arguments and settings changes. `sync(apply: true)` executes vendor commands outside scope and shared-resource locks. It observes host state after each -command, including failures and timeouts. Codex toggles use fresh TOML bytes -under the existing Codex config coordination routes. Antigravity project -registration edits the workspace discovery manifest under the project lock. -Claude Code uses host commands with its selected user, project, or local scope. +command, including failures, timeouts, and cancellation of an in-flight +command. Cancellation preserves completed results. Codex and Antigravity +project settings changes use recoverable native file publication. Codex uses +the existing config coordination routes and defers to any private MCP +materialization receipt on the same file. Project settings edits require a +physical destination within project authority. Claude Code uses host commands +with its selected user, project, or local scope. The manifest's `hostPlugin` declaration takes explicit recipients and either a marketplace ID or one source-backed bundle. Source-backed inspection reads a -local checkout and uses the host's catalog identity where required. Host -installation and enablement are reconciled with the vendor's records. +local checkout, including active exported groups from local producers, and +verifies the host marketplace origin or registered project bundle path before +reconciling an existing registration. Conflicting enablement declarations for +one host, scope and plugin ID are surfaced before execution. The combined update graph continues to freeze and replay `kind: plugin` through its existing resource and transaction path. `SkillGovernance.inspect` compares declared host plugin state with observed installation and enablement, and checks the merged project and user scan roots against effectively enabled plugin skills. Collisions report parsed names and -physical file identity. Its advisory budgets estimate the UTF-8 bytes of +physical file identity, with host-visible plugin namespaces for Antigravity and +Claude Code. Its advisory budgets estimate the UTF-8 bytes of deduplicated names and descriptions, excluding per-skill framing and host built-ins. The default advisory threshold is 8,000. Claude Code can supply a threshold through `SLASH_COMMAND_TOOL_CHAR_BUDGET`. The optional budgets are diff --git a/Documentation/Reference/ManifestSchema.md b/Documentation/Reference/ManifestSchema.md index 35be20a..8ebb6d8 100644 --- a/Documentation/Reference/ManifestSchema.md +++ b/Documentation/Reference/ManifestSchema.md @@ -609,7 +609,7 @@ Declare a plugin for explicit host synchronization. | --- | --- | --- | --- | | `kind` | yes | `hostPlugin` | Selects a plugin managed by an explicit host synchronization. | | `name` | yes | string | Symbolic name of the declaration. | -| `agents` | yes | sequence of agent (at most 10000 items) | Explicit recipients. A marketplace ID requires one recipient. A bundle requires at least one. | +| `agents` | yes | sequence of agent (exactly 1 item) | One explicit recipient for the marketplace plugin. | | `enabled` | | boolean | Desired host enablement. Omission defaults to true. | | `claudeScope` | | `user` / `project` / `local` | Claude Code scope. Omission uses the selected agents scope. | | `pluginId` | yes | string | Host plugin ID. | @@ -623,7 +623,7 @@ Declare a plugin for explicit host synchronization. | --- | --- | --- | --- | | `kind` | yes | `hostPlugin` | Selects a plugin managed by an explicit host synchronization. | | `name` | yes | string | Symbolic name of the declaration. | -| `agents` | yes | sequence of agent (at most 10000 items) | Explicit recipients. A marketplace ID requires one recipient. A bundle requires at least one. | +| `agents` | yes | sequence of agent (1 to 10000 items) | One or more explicit recipients for the bundle. | | `enabled` | | boolean | Desired host enablement. Omission defaults to true. | | `claudeScope` | | `user` / `project` / `local` | Claude Code scope. Omission uses the selected agents scope. | | `source` | yes | string | Source alias containing the plugin bundle. | diff --git a/Scripts/generate-manifest-schema.py b/Scripts/generate-manifest-schema.py index c6182ff..9c84099 100644 --- a/Scripts/generate-manifest-schema.py +++ b/Scripts/generate-manifest-schema.py @@ -93,11 +93,15 @@ def allow(keys): bounds += ', maximum: ' + integer(value['maximum'], 'maximum') return '.integer(' + bounds + ')' if kind == 'array': - allow({'type', 'items', 'maxItems'}) + allow({'type', 'items', 'minItems', 'maxItems'}) if 'items' not in value: raise ValueError('arrays require an item shape') + minimum = integer(value['minItems'], 'minItems', 0) if 'minItems' in value else None maximum = integer(value['maxItems'], 'maxItems', 0) if 'maxItems' in value else 'nil' - return '.array(' + emit(value['items'], definitions) + ', maximum: ' + maximum + ')' + if minimum is not None and maximum != 'nil' and int(minimum) > int(maximum): + raise ValueError('minItems cannot exceed maxItems') + bounds = (', minimum: ' + minimum if minimum is not None else '') + ', maximum: ' + maximum + return '.array(' + emit(value['items'], definitions) + bounds + ')' if kind == 'object': allow({'type', 'properties', 'required', 'additionalProperties', 'maxProperties'}) maximum = integer(value['maxProperties'], 'maxProperties', 0) if 'maxProperties' in value else 'nil' @@ -135,7 +139,14 @@ def describe(value): 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 '') + minimum = value.get('minItems') + maximum = value.get('maxItems') + if minimum is not None and maximum is not None: + return shape + (f" (exactly {minimum} {'item' if minimum == 1 else 'items'})" if minimum == maximum + else f" ({minimum} to {maximum} items)") + if minimum is not None: + return shape + f" (at least {minimum} items)" + return shape + (f" (at most {maximum} items)" if maximum is not None else '') if kind == 'object': shape = ('name → ' + describe(value['additionalProperties']) if isinstance(value['additionalProperties'], dict) else 'mapping') diff --git a/Scripts/test_manifest_schema.py b/Scripts/test_manifest_schema.py index 78dc5b7..2049301 100644 --- a/Scripts/test_manifest_schema.py +++ b/Scripts/test_manifest_schema.py @@ -2,6 +2,7 @@ """Guard the bundled schema compiler's accepted validation semantics.""" import copy import importlib.util +import json import unittest from pathlib import Path @@ -56,6 +57,23 @@ def test_schema_values_drive_runtime_constraints_and_help(self): 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_host_plugin_recipients_are_required_and_bounded_by_selector(self): + schema = json.loads((Path(__file__).parents[1] / + 'Sources/AgentsManifest/Resources/agents.schema.json').read_text()) + marketplace = schema['$defs']['component_hostPluginID'] + bundle = schema['$defs']['component_hostPluginBundle'] + self.assertIn('agents', marketplace['required']) + self.assertIn('agents', bundle['required']) + self.assertEqual(marketplace['properties']['agents']['minItems'], 1) + self.assertEqual(marketplace['properties']['agents']['maxItems'], 1) + self.assertEqual(bundle['properties']['agents']['minItems'], 1) + swift, help_text = compiler.compile_schema(schema) + self.assertIn('minimum: 1, maximum: 1)', swift) + self.assertIn('exactly 1 item', help_text) + with self.assertRaises(ValueError): + compiler.emit({'type': 'array', 'items': {'type': 'string'}, + 'minItems': 2, 'maxItems': 1}, {}) + 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']}]: diff --git a/Sources/AgentsCore/HostPluginConfiguration.swift b/Sources/AgentsCore/HostPluginConfiguration.swift index 1dda3ff..67a25cd 100644 --- a/Sources/AgentsCore/HostPluginConfiguration.swift +++ b/Sources/AgentsCore/HostPluginConfiguration.swift @@ -1,74 +1,75 @@ import Foundation -/// Settings edits coordinate with the same physical writers as native component updates. +/// Settings edits use the native file's coordination and journal. Vendor commands run separately. package enum HostPluginConfigurationRoute { case codex, antigravityProject - package func edit( - store: StateStore, maximumFileBytes: Int, transform: (Data?) throws -> Data? - ) throws { - let codexRoute: NativeTargetRoute = store.scope == .user ? .codexMCPUser : .codexMCPProject - let routes: Set = self == .codex ? [codexRoute] : [] - try store.withLock(footprint: routes) { - let destination: URL - switch self { - case .codex: - destination = try store.nativeTarget(for: codexRoute).url - case .antigravityProject: - guard store.scope == .project else { throw CoreError.unsafePath("expected project scope") } - let root = NativeRootAuthority( - loader: store.environment.projectDirectory, descendants: [".agents"]) - destination = try root.physicalDirectory().appendingPathComponent("plugins.json") - try store.requireProjectNativeAuthority(at: destination) - } - try edit(destination, maximumFileBytes: maximumFileBytes, transform: transform) + private func route(_ scope: InstallScope) -> NativeTargetRoute { + switch self { + case .codex: return scope == .user ? .codexMCPUser : .codexMCPProject + case .antigravityProject: return .antigravityPluginsProject } } - private func edit( - _ destination: URL, maximumFileBytes: Int, transform: (Data?) throws -> Data? - ) throws { - let before = try TargetPrecondition.readingFile(destination, maximumFileBytes: maximumFileBytes) - guard let after = try transform(before.bytes), after != before.bytes else { return } - let parentURL = destination.deletingLastPathComponent() - let parent = try DirectoryHandle(at: parentURL, create: true) - let name = destination.lastPathComponent - let staging = ".host-plugin-" + UUID().uuidString - let temporary = try parent.makeDirectory(staging, syncParent: false) - let temporaryIdentity = try temporary.objectIdentity - var cleanStaging = true - defer { - if cleanStaging { try? parent.remove(staging, identity: temporaryIdentity) } + private func requireScope(_ store: StateStore) throws { + let route = route(store.scope) + guard route.permits(store.scope) else { + throw CoreError.unsupported("Plugin settings route requires project scope.") } - try temporary.write( - name, data: after, preservingMetadataOf: before.evidence.exists ? name : nil, - originalParent: parent, syncParent: false) - try before.evidence.validate() - guard try DirectoryHandle(at: parentURL).objectIdentity == parent.objectIdentity else { - throw CoreError.invalidState("host configuration parent changed") + guard store.scope == .project else { return } + let file = try route.physicalDirectory(store.environment).appendingPathComponent(route.basename) + try requireProjectAuthority(file, store: store) + } + + private func requireProjectAuthority(_ file: URL, store: StateStore) throws { + guard store.scope == .project else { return } + let project = store.environment.projectDirectory.resolvingSymlinksInPath() + guard PathSafety.isContained(file, in: project), + try NativeTargetRoute.userRoute(at: file, environment: store.environment) == nil + else { + throw CoreError.unsupported( + "The project plugin settings resolve outside project authority. Use user scope for user settings." + ) } - if !before.evidence.exists { - try temporary.move(name, to: parent, named: name, mode: .exclusive) - return + } + + private func editableTarget(_ store: StateStore) throws -> MaterializationTarget { + try requireScope(store) + let target = try store.nativeTarget(for: route(store.scope)) + try requireProjectAuthority(target.url, store: store) + if self == .codex, try store.hasMaterializationReceipt(for: target) { + throw CoreError.unsupported( + "Codex settings contain a private MCP materialization. Reconcile it before syncing host plugins." + ) } - let candidate = try FileSnapshot.capture( - name, from: temporary, maximumFileBytes: maximumFileBytes) - try temporary.atomicRename(name, to: parent, named: name, mode: .exchange) - .requireSuccess("replace host plugin configuration") - cleanStaging = false - // Restore the displaced object even if it is no longer a readable configuration file. - if let displaced = try? FileSnapshot.capture( - name, from: temporary, maximumFileBytes: maximumFileBytes), - displaced.snapshot == before.evidence.snapshot - { - cleanStaging = true - try parent.sync() - return + return target + } + + package func validateScope(store: StateStore) throws { + try requireScope(store) + } + + package func checkEditable(store: StateStore) throws { + try requireScope(store) + try store.withReadLock(footprint: [route(store.scope)]) { + _ = try editableTarget(store) } - if try parent.info(name).map({ FileObjectIdentity($0) }) == candidate.snapshot?.identity { - try temporary.move(name, to: parent, named: name, mode: .exchange) - cleanStaging = true + } + + package func edit( + store: StateStore, maximumFileBytes: Int, + checkpoint: @escaping (String) throws -> Void = { _ in }, + transform: (Data?) throws -> Data? + ) throws { + try requireScope(store) + try store.withLock(footprint: [route(store.scope)]) { + let target = try editableTarget(store) + let before = try TargetPrecondition.readingFile( + target.url, maximumFileBytes: maximumFileBytes) + guard let after = try transform(before.bytes), after != before.bytes else { return } + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + try transaction.replace(target.url, with: .data(after), expecting: before.evidence) + try transaction.commit() } - throw CoreError.invalidState("host configuration changed during publication") } } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 7a397cd..a20157d 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -23,6 +23,7 @@ enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { case claudeSettingsUser = "claude.settings.user" case codexHooksProject = "codex.hooks.project" case codexHooksUser = "codex.hooks.user" + case antigravityPluginsProject = "antigravity.plugins.project" case antigravityHooksProject = "antigravity.hooks.project" case antigravityHooksUser = "antigravity.hooks.user" case cursorHooksProject = "cursor.hooks.project" @@ -59,6 +60,7 @@ enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { case .claudeSettingsProject, .claudeSettingsUser: "settings.json" case .codexHooksProject, .codexHooksUser, .cursorHooksProject, .cursorHooksUser: "hooks.json" case .antigravityHooksProject, .antigravityHooksUser: "hooks.json" + case .antigravityPluginsProject: "plugins.json" case .antigravityMCPProject, .antigravityMCPUser: "mcp_config.json" case .geminiIgnoreProject: ".geminiignore" case .cursorIgnoreProject: ".cursorignore" @@ -128,7 +130,7 @@ enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { return root } return try home().appendingPathComponent(".codex") - case .antigravityMCPProject, .antigravityHooksProject: + case .antigravityMCPProject, .antigravityHooksProject, .antigravityPluginsProject: return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( ".agents") case .antigravityMCPUser, .antigravityHooksUser: @@ -258,6 +260,7 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable package static let codexMCPUser = Self(.codexMCPUser) package static let antigravityMCPProject = Self(.antigravityMCPProject) package static let antigravityMCPUser = Self(.antigravityMCPUser) + package static let antigravityPluginsProject = Self(.antigravityPluginsProject) package static let antigravityHooksProject = Self(.antigravityHooksProject) package static let antigravityHooksUser = Self(.antigravityHooksUser) package static let geminiMCPProject = Self(.geminiMCPProject) @@ -369,7 +372,7 @@ package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable throws -> NativeRootAuthority { switch fixed { - case .antigravityMCPProject, .antigravityHooksProject: + case .antigravityMCPProject, .antigravityHooksProject, .antigravityPluginsProject: return .init(loader: environment.projectDirectory, descendants: [".agents"]) case .antigravityMCPUser, .antigravityHooksUser: return .init(loader: environment.homeDirectory, descendants: [".gemini", "config"]) diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index 6e88b6f..f8fc23e 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -101,6 +101,17 @@ extension StateStore { return MaterializationTarget(url: url.standardizedFileURL, path: path, scope: directory) } + /// A stale receipt still owns the file and must block independent settings writers. + func hasMaterializationReceipt(for target: MaterializationTarget) throws -> Bool { + if let route = try TransactionPaths(store: self).coordinationRoute(for: target.path), + try TransactionLockContext.current(self)?.absentRoot(for: route) != nil + { + return false + } + return try materializationReceipts(for: target.path).records.targets[ + materializationReceiptKey(for: target.path)] != nil + } + /// Inspects the last local generation under the caller's scope lock, without exposing bytes. package func materializationReceipt(for target: MaterializationTarget) throws -> MaterializationReceipt? diff --git a/Sources/AgentsManifest/ManifestSchema.swift b/Sources/AgentsManifest/ManifestSchema.swift index 6b75e9b..e770816 100644 --- a/Sources/AgentsManifest/ManifestSchema.swift +++ b/Sources/AgentsManifest/ManifestSchema.swift @@ -263,14 +263,14 @@ enum ManifestSchema { "component_hostPluginID": .object( [ "kind": .constant("hostPlugin"), "name": .string, - "agents": .array(.named("agent"), maximum: 10000), "enabled": .boolean, + "agents": .array(.named("agent"), minimum: 1, maximum: 1), "enabled": .boolean, "claudeScope": .enumeration(["user", "project", "local"]), "pluginId": .string, "marketplace": .string, ], required: ["kind", "name", "agents", "pluginId"], maximum: nil), "component_hostPluginBundle": .object( [ "kind": .constant("hostPlugin"), "name": .string, - "agents": .array(.named("agent"), maximum: 10000), "enabled": .boolean, + "agents": .array(.named("agent"), minimum: 1, maximum: 10000), "enabled": .boolean, "claudeScope": .enumeration(["user", "project", "local"]), "source": .string, "path": .string, ], required: ["kind", "name", "agents", "source", "path"], maximum: nil), diff --git a/Sources/AgentsManifest/Resources/agents.schema.json b/Sources/AgentsManifest/Resources/agents.schema.json index 7baa4b4..c5e05ee 100644 --- a/Sources/AgentsManifest/Resources/agents.schema.json +++ b/Sources/AgentsManifest/Resources/agents.schema.json @@ -1766,8 +1766,9 @@ "items": { "$ref": "#/$defs/agent" }, - "maxItems": 10000, - "description": "Explicit recipients. A marketplace ID requires one recipient. A bundle requires at least one." + "minItems": 1, + "maxItems": 1, + "description": "One explicit recipient for the marketplace plugin." }, "enabled": { "type": "boolean", @@ -1816,8 +1817,9 @@ "items": { "$ref": "#/$defs/agent" }, + "minItems": 1, "maxItems": 10000, - "description": "Explicit recipients. A marketplace ID requires one recipient. A bundle requires at least one." + "description": "One or more explicit recipients for the bundle." }, "enabled": { "type": "boolean", diff --git a/Sources/AgentsManifest/YAMLValidation.swift b/Sources/AgentsManifest/YAMLValidation.swift index af0c739..58fe5a2 100644 --- a/Sources/AgentsManifest/YAMLValidation.swift +++ b/Sources/AgentsManifest/YAMLValidation.swift @@ -8,7 +8,7 @@ indirect enum YAMLRule: Sendable { case constant(String) case enumeration([String]) case named(String) - case array(YAMLRule, maximum: Int?) + case array(YAMLRule, minimum: Int = 0, maximum: Int?) case dictionary(YAMLRule, maximum: Int?) case object([String: YAMLRule], required: [String], maximum: Int?) case oneOf([YAMLRule]) @@ -115,8 +115,11 @@ final class YAMLValidation { if let maximum, integer > maximum { throw fail("integer exceeds its maximum") } default: break } - case .array(let item, let maximum): + case .array(let item, let minimum, let maximum): guard let items = node.items else { throw fail("expected a sequence") } + guard items.count >= minimum else { + throw fail("sequence has fewer than minItems: \(minimum)") + } if let maximum, items.count > maximum { throw fail("sequence exceeds maxItems: \(maximum)") } for node in items { try check(node, item) } case .dictionary(let value, let maximum): diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift index 5eb6a60..578e839 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift @@ -51,6 +51,7 @@ public enum HostPluginExecutor { .map { plan($0, locations: locations).preview } } + /// Cancellation reconciles any in-flight command and returns the targets already attempted. public static func sync( scope: InstallScope = .project, agents: [AgentID]? = nil, apply: Bool = false, environment: RuntimeEnvironment = .init(), @@ -68,22 +69,22 @@ public enum HostPluginExecutor { var result: [HostPluginSyncResult] = [] for target in targets { - try Task.checkCancellation() + if Task.isCancelled { break } result.append(await applyTarget(target, locations: locations, runner: runner)) } return result } - private enum CommandRole { + private enum CommandRole: Sendable { case marketplace, validate, install, toggle } - private struct Command { + private struct Command: Sendable { let role: CommandRole let argv: [String] } - private struct Plan { + private struct Plan: Sendable { let preview: HostPluginPreview let commands: [Command] let edits: [HostPluginConfigurationChange] @@ -92,7 +93,6 @@ public enum HostPluginExecutor { private static func plan( _ target: HostPluginTarget, locations: HostPluginLocations ) -> Plan { - let enabled = target.declaration.enabled var observed: ObservedHostPlugin? func report( _ drift: HostPluginDrift, _ reason: String? = nil, commands: [Command] = [], @@ -100,7 +100,7 @@ public enum HostPluginExecutor { ) -> Plan { let status = HostPluginStatus( agent: target.agent, scope: target.scope, claudeScope: target.claudeScope, - name: target.declaration.name, pluginId: target.id, desiredEnabled: enabled, + name: target.name, pluginId: target.id, desiredEnabled: target.enabled, installed: observed?.installed, explicitEnabled: observed?.explicit, effectiveEnabled: observed?.effective, locations: observed?.locations ?? [], drift: drift, diagnostic: reason) @@ -110,25 +110,71 @@ public enum HostPluginExecutor { commands: commands, edits: edits) } if let issue = target.issue { return report(issue.0, issue.1) } - guard let id = target.id else { return report(.unverified, "Host plugin ID is unavailable.") } + guard let id = target.id, let enabled = target.enabled else { + return report(.unverified, "Host plugin declaration could not be resolved.") + } do { + let store = StateStore(scope: target.scope, environment: locations.environment) + if target.agent == .codex { + try HostPluginConfigurationRoute.codex.validateScope(store: store) + } let inventory = try locations.inventory( - agent: target.agent, scope: target.scope, claudeScope: target.claudeScope) + agent: target.agent, scope: target.scope, claudeScope: target.claudeScope, + verifyMarketplace: target.marketplaceSource != nil) observed = inventory.plugins[id] ?? .init(id: id, name: id, installed: false) - if target.agent == .antigravity, target.scope == .project, target.bundle != nil, - observed?.projectRegistered != true - { - observed?.installed = false + var needsMarketplace = false + if let source = target.marketplaceSource, let catalog = target.marketplaceName { + let registrations = inventory.marketplaces[catalog] + let origins = (registrations ?? []) + (inventory.declaredMarketplaces[catalog] ?? []) + guard + origins.allSatisfy({ origin in + origin.map { sameMarketplace($0, as: source) } ?? false + }) + else { + return report( + .unsupported, + "Marketplace '\(catalog)' has different or unverifiable provenance. Reconcile its registration with the declared source." + ) + } + if registrations != nil { + needsMarketplace = false + } else if observed?.installed == true { + return report( + .unverified, "The installed plugin's marketplace source could not be verified.") + } else { + needsMarketplace = true + } } - if target.agent == .antigravity, enabled { - if target.scope == .project, observed?.globalDisabled == true { - return report( - .unsupported, "Project scope cannot re-enable a globally disabled Antigravity plugin.") + if target.agent == .antigravity { + if target.scope == .project, let bundle = target.bundle { + if let registered = observed?.projectBundle { + guard let intended = PathSafety.realPath(bundle.path), + PathSafety.realPath(registered.path) == intended + else { + return report( + .unsupported, + "A different Antigravity project bundle already uses directory name '\(id)'.") + } + } else { + observed?.installed = false + } } - if observed?.manifestDisabled == true { - return report(.unsupported, "The Antigravity plugin manifest disables the plugin.") + if enabled { + if target.scope == .project, observed?.globalDisabled == true { + return report( + .unsupported, "Project scope cannot re-enable a globally disabled Antigravity plugin." + ) + } + if inventory.inheritedExclusions.contains(id) { + return report( + .unsupported, + "The Antigravity plugin is excluded by a personal or inherited discovery manifest.") + } + if target.manifestDisabled || observed?.manifestDisabled == true { + return report(.unsupported, "The Antigravity plugin manifest disables the plugin.") + } } } @@ -136,6 +182,14 @@ public enum HostPluginExecutor { let toggle = observed?.effective != enabled || observed?.explicit.map { $0 != enabled } == true if !missing && !toggle { return report(.current) } + if target.agent == .codex { + if toggle { try HostPluginConfigurationRoute.codex.checkEditable(store: store) } + // Codex CLI installation and marketplace registration write user settings. + if missing, target.scope == .project { + try HostPluginConfigurationRoute.codex.checkEditable( + store: StateStore(scope: .user, environment: locations.environment)) + } + } var commands: [Command] = [] var changes: [HostPluginConfigurationChange] = [] var edits: [HostPluginConfigurationChange] = [] @@ -156,9 +210,7 @@ public enum HostPluginExecutor { switch target.agent { case .codex: if missing { - if let source = target.marketplaceSource, let catalog = target.marketplaceName, - !inventory.marketplaces.contains(catalog) - { + if needsMarketplace, let source = target.marketplaceSource { command(.marketplace, ["codex", "plugin", "marketplace", "add", source]) } command(.install, ["codex", "plugin", "add", id, "--json"]) @@ -174,9 +226,7 @@ public enum HostPluginExecutor { let scope = target.claudeScope! let args = ["--scope", scope.rawValue] if missing { - if let source = target.marketplaceSource, let catalog = target.marketplaceName, - !inventory.marketplaces.contains(catalog) - { + if needsMarketplace, let source = target.marketplaceSource { command(.marketplace, ["claude", "plugin", "marketplace", "add", source]) } command(.install, ["claude", "plugin", "install", id] + args) @@ -194,7 +244,7 @@ public enum HostPluginExecutor { if let bundle = target.bundle { command(.validate, ["agy", "plugin", "validate", bundle.path]) selector = bundle.path - } else if case .marketplace(let raw, _) = target.declaration.selector { + } else if case .marketplace(let raw, _)? = target.selector { selector = raw } else { return report( @@ -240,11 +290,29 @@ public enum HostPluginExecutor { missing ? (observed?.installed == nil ? .unverified : .missing) : .enablement return report(drift, commands: commands, changes: changes, edits: edits) + } catch CoreError.unsupported(let reason) { + return report(.unsupported, reason) } catch { return report(.unverified, "Host plugin inventory could not be read.") } } + private static func sameMarketplace(_ observed: String, as expected: String) -> Bool { + if observed.hasPrefix("/") || expected.hasPrefix("/") { + guard observed.hasPrefix("/"), expected.hasPrefix("/"), + let physical = PathSafety.realPath(observed) + else { return false } + return PathSafety.realPath(expected) == physical + } + func origin(_ value: String) -> SourceOrigin? { + let path = value.split(separator: "/", omittingEmptySubsequences: false) + let shorthand = path.count == 2 && !path[0].contains(".") && !value.contains("@") + return try? .git(shorthand ? "https://github.com/" + value : value) + } + guard let actual = origin(observed) else { return observed == expected } + return actual == origin(expected) + } + private static func applyTarget( _ target: HostPluginTarget, locations: HostPluginLocations, runner: any HostPluginCommandRunner ) async -> HostPluginSyncResult { @@ -270,6 +338,10 @@ public enum HostPluginExecutor { } ran.append(command.argv) let result = await runner.run(argv: command.argv, environment: locations.environment) + if Task.isCancelled { + current = await Task.detached { plan(target, locations: locations) }.value + return finish(.failed, "Host plugin synchronization was cancelled.") + } current = plan(target, locations: locations) switch result { case .success: @@ -294,6 +366,9 @@ public enum HostPluginExecutor { installed = true } continue + } catch CoreError.unsupported(let reason) { + current = plan(target, locations: locations) + return finish(.unsupported, reason) } catch { current = plan(target, locations: locations) return finish(.failed, "Host plugin settings could not be edited.") @@ -303,7 +378,7 @@ public enum HostPluginExecutor { return finish(.failed, "Host readback could not verify the declared plugin state.") } if installed { return finish(.installed) } - if edited || !ran.isEmpty { return finish(target.declaration.enabled ? .enabled : .disabled) } + if edited || !ran.isEmpty { return finish(target.enabled == true ? .enabled : .disabled) } return finish(.unchanged) } return finish(.failed, "Host plugin synchronization was cancelled.") @@ -345,7 +420,7 @@ public enum HostPluginExecutor { let id = target.id! let before = try HostPluginDocuments.strings(existing?.value) var after = before.filter { $0 != id } - if !target.declaration.enabled { after.append(id) } + if target.enabled == false { after.append(id) } if before != after { edits.append( .put( diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift index e53f122..4068dfc 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift @@ -10,17 +10,20 @@ struct ObservedHostPlugin { var effective: Bool? var locations: [URL] = [] var globalDisabled = false - var projectRegistered = false + var projectBundle: URL? var manifestDisabled = false } struct HostPluginInventory { var plugins: [String: ObservedHostPlugin] = [:] - var marketplaces: Set = [] + /// A record with an unknown origin still reserves the host's marketplace name. + var marketplaces: [String: [String?]] = [:] + var declaredMarketplaces: [String: [String?]] = [:] var exclusions: [String] = [] + var inheritedExclusions: Set = [] } -struct HostPluginLocations { +struct HostPluginLocations: Sendable { let environment: RuntimeEnvironment var project: URL { environment.projectDirectory } var codexUser: URL { @@ -47,26 +50,41 @@ struct HostPluginLocations { } } - func inventory(agent: AgentID, scope: InstallScope, claudeScope: ClaudePluginScope? = nil) - throws -> HostPluginInventory - { + func inventory( + agent: AgentID, scope: InstallScope, claudeScope: ClaudePluginScope? = nil, + verifyMarketplace: Bool = false + ) throws -> HostPluginInventory { switch agent { - case .codex: return try codex(scope) + case .codex: return try codex(scope, verifyMarketplace: verifyMarketplace) case .claudeCode: - return try claude(claudeScope ?? (scope == .user ? .user : .project), scope: scope) + return try claude( + claudeScope ?? (scope == .user ? .user : .project), scope: scope, + verifyMarketplace: verifyMarketplace) case .antigravity: return try antigravity(scope) default: return .init() } } - private func codex(_ scope: InstallScope) throws -> HostPluginInventory { + private func codex(_ scope: InstallScope, verifyMarketplace: Bool) throws -> HostPluginInventory { let user = try HostPluginDocuments.read(codexConfig(.user), format: .toml) + // The install command runs from the project even when its requested settings scope is user. let local = - scope == .project + scope == .project || verifyMarketplace ? try HostPluginDocuments.read(codexConfig(.project), format: .toml) : nil let globalEntries = try HostPluginDocuments.fields(user?.hostValue(["plugins"])) - let localEntries = try HostPluginDocuments.fields(local?.hostValue(["plugins"])) - let marketplaceEntries = try HostPluginDocuments.fields(user?.hostValue(["marketplaces"])) + let localEntries = try HostPluginDocuments.fields( + scope == .project ? local?.hostValue(["plugins"]) : nil) + var result = HostPluginInventory() + for document in [user, local] { + let registrations = try HostPluginDocuments.fields(document?.hostValue(["marketplaces"])) + for (name, value) in registrations { + let fields = try HostPluginDocuments.fields(value) + let type = fields["source_type"]?.hostString + let origin = fields["source"]?.hostString + result.marketplaces[name, default: []].append( + (type == "local" || type == "git") && fields["ref_name"] == nil ? origin : nil) + } + } var cache: [String: URL] = [:] let cacheRoot = codexUser.appendingPathComponent("plugins/cache") for marketplace in try HostPluginDocuments.directory(cacheRoot) @@ -82,16 +100,20 @@ struct HostPluginLocations { } } } + let catalogPath = ".agents/plugins/marketplace.json" + let personal = try HostMarketplace.read(at: environment.homeDirectory, manifest: catalogPath) + let workspace = + scope == .project || verifyMarketplace + ? try HostMarketplace.read(at: project, manifest: catalogPath) : nil + for catalog in [personal, workspace].compactMap({ $0 }) { + result.marketplaces[catalog.name, default: []].append(catalog.root.path) + } var catalogBundles: [String: URL] = [:] - if scope == .project, - let catalog = try HostMarketplace.read( - at: project, manifest: ".agents/plugins/marketplace.json") - { + if scope == .project { for id in localEntries.keys { - if let bundle = try catalog.localBundle(for: id) { catalogBundles[id] = bundle } + if let bundle = try workspace?.localBundle(for: id) { catalogBundles[id] = bundle } } } - var result = HostPluginInventory(marketplaces: Set(marketplaceEntries.keys)) for id in Set(cache.keys).union(globalEntries.keys).union(localEntries.keys).sorted() { let global = try HostPluginDocuments.fields(globalEntries[id]) let project = try HostPluginDocuments.fields(localEntries[id]) @@ -117,26 +139,35 @@ struct HostPluginLocations { return false } - private func claude(_ selection: ClaudePluginScope, scope: InstallScope) throws - -> HostPluginInventory - { + private func claude( + _ selection: ClaudePluginScope, scope: InstallScope, verifyMarketplace: Bool + ) throws -> HostPluginInventory { let registry = try HostPluginDocuments.read( claudeUser.appendingPathComponent("plugins/installed_plugins.json")) let entries = try HostPluginDocuments.fields(registry?.hostValue(["plugins"])) - let scopes: [ClaudePluginScope] = - scope == .user && selection == .user - ? [.user] : [.user, .project, .local] + let levels: [ClaudePluginScope] = [.user, .project, .local] + let scopes = scope == .user && selection == .user ? [.user] : levels + var result = HostPluginInventory() var settings: [ClaudePluginScope: [String: NativeValue]] = [:] - for level in scopes { + for level in verifyMarketplace ? levels : scopes { let document = try HostPluginDocuments.read( claudeSettings(level), format: .jsonc(trailingCommas: true)) - settings[level] = try HostPluginDocuments.fields(document?.hostValue(["enabledPlugins"])) + if scopes.contains(level) { + settings[level] = try HostPluginDocuments.fields(document?.hostValue(["enabledPlugins"])) + } + if verifyMarketplace { + let declared = try HostPluginDocuments.fields( + document?.hostValue(["extraKnownMarketplaces"])) + for (name, value) in declared { + try result.declaredMarketplaces[name, default: []].append(claudeMarketplaceOrigin(value)) + } + } } let market = try HostPluginDocuments.read( claudeUser.appendingPathComponent("plugins/known_marketplaces.json")) - var result = HostPluginInventory( - marketplaces: Set( - try HostPluginDocuments.fields(market?.hostValue([])).keys)) + for (name, value) in try HostPluginDocuments.fields(market?.hostValue([])) { + try result.marketplaces[name, default: []].append(claudeMarketplaceOrigin(value)) + } let ids = settings.values.reduce(into: Set(entries.keys)) { $0.formUnion($1.keys) } for id in ids.sorted() { let installations = try HostPluginDocuments.list(entries[id]).map { @@ -160,52 +191,85 @@ struct HostPluginLocations { installations.filter { $0.0 == level }.compactMap(\.1).sorted { $0.path < $1.path } }.filter(Self.isDirectory) let explicit = try HostPluginDocuments.boolean(settings[selection]?[id]) - let effective = try scopes.reversed().lazy.compactMap { + let configured = try scopes.reversed().lazy.compactMap { try HostPluginDocuments.boolean(settings[$0]?[id]) }.first let installed = selected.isEmpty ? false : selected.contains { $0.1.map(Self.isDirectory) == true } + let manifest = try locations.first.flatMap { + try HostPluginDocuments.read($0.appendingPathComponent(".claude-plugin/plugin.json")) + } + let name = + try manifest?.hostValue(["name"])?.hostString + ?? String(id.split(separator: "@").first ?? Substring(id)) + let defaultEnabled = try HostPluginDocuments.boolean(manifest?.hostValue(["defaultEnabled"])) result.plugins[id] = .init( - id: id, name: String(id.split(separator: "@").first ?? Substring(id)), - installed: installed, explicit: explicit, - effective: locations.isEmpty ? nil : (effective ?? true), locations: locations) + id: id, name: name, installed: installed, explicit: explicit, + effective: locations.isEmpty ? nil : (configured ?? defaultEnabled ?? true), + locations: locations) } return result } + private func claudeMarketplaceOrigin(_ record: NativeValue) throws -> String? { + let fields = try HostPluginDocuments.fields(record) + let source = try HostPluginDocuments.fields(fields["source"]) + switch source["source"]?.hostString { + case "directory": + return source["path"]?.hostString.flatMap { $0.hasPrefix("/") ? $0 : nil } + case "file": + guard let path = source["path"]?.hostString, path.hasPrefix("/") else { return nil } + let file = URL(fileURLWithPath: path) + guard file.lastPathComponent == "marketplace.json", + file.deletingLastPathComponent().lastPathComponent == ".claude-plugin" + else { return nil } + return file.deletingLastPathComponent().deletingLastPathComponent().path + case "git", "url": + return source["ref"] == nil ? source["url"]?.hostString : nil + case "github": + return source["ref"] == nil ? source["repo"]?.hostString : nil + default: return nil + } + } + private func antigravity(_ scope: InstallScope) throws -> HostPluginInventory { let config = try HostPluginDocuments.read(antigravityUser.appendingPathComponent("config.json")) let settings = try HostPluginDocuments.fields(config?.hostValue(["plugins"])) - let user = try antigravityBundles(at: antigravityUser.appendingPathComponent("plugins")) - var project: [String: (name: String, url: URL, disabled: Bool)] = [:] + var user = try antigravityBundles(at: antigravityUser.appendingPathComponent("plugins")) + var discovery = AntigravityDiscoveryTraversal() + let personal = try antigravityEntries( + in: antigravityUser.appendingPathComponent("plugins.json"), + base: antigravityUser, depth: 0, traversal: &discovery) + user.merge(personal.bundles) { first, _ in first } + var project: [String: AntigravityBundle] = [:] var exclusions: [String] = [] + var inheritedExclusions = personal.exclusions if scope == .project { - let manifest = try HostPluginDocuments.read(antigravityProject) - exclusions = try HostPluginDocuments.strings(manifest?.hostValue(["exclude"])) project = try antigravityBundles(at: self.project.appendingPathComponent(".agents/plugins")) - var visited = Set() - for (id, bundle) in try antigravityEntries( - in: antigravityProject, base: self.project, depth: 0, visited: &visited) - where project[id] == nil { - project[id] = bundle - } + let discoveries = try antigravityEntries( + in: antigravityProject, base: self.project, depth: 0, traversal: &discovery) + project.merge(discoveries.bundles) { first, _ in first } + exclusions = discoveries.ownExclusions + inheritedExclusions.formUnion(discoveries.inheritedExclusions) } - var result = HostPluginInventory(exclusions: exclusions) + var result = HostPluginInventory( + exclusions: exclusions, inheritedExclusions: inheritedExclusions) for id in Set(user.keys).union(project.keys).union(settings.keys).sorted() { let global = user[id] let local = project[id] let entry = try HostPluginDocuments.fields(settings[id]) let toggle = try HostPluginDocuments.boolean(entry["enabled"]) - let excluded = exclusions.contains(id) + let excluded = exclusions.contains(id) || inheritedExclusions.contains(id) + let globalDisabled = global?.disabled == true || toggle == false let bundle = local ?? global let disabled = bundle?.disabled == true result.plugins[id] = .init( id: id, name: bundle?.name ?? id, installed: bundle != nil, explicit: scope == .user ? toggle : (excluded ? false : nil), - effective: bundle == nil ? nil : !excluded && !disabled && toggle != false, + effective: bundle == nil ? nil : !excluded && !disabled && !globalDisabled, locations: bundle.map { [$0.url] } ?? [], - globalDisabled: global?.disabled == true || toggle == false, - projectRegistered: local != nil, + globalDisabled: globalDisabled, + projectBundle: local?.url, manifestDisabled: disabled) } return result @@ -243,21 +307,40 @@ struct HostPluginLocations { return nil } + private struct AntigravityDiscoveries { + var bundles: [String: AntigravityBundle] = [:] + var ownExclusions: [String] = [] + var inheritedExclusions: Set = [] + var exclusions: Set { inheritedExclusions.union(ownExclusions) } + } + + private struct AntigravityDiscoveryTraversal { + var active = Set() + var read: [[String]: AntigravityDiscoveries] = [:] + } + private func antigravityEntries( - in file: URL, base: URL, depth: Int, visited: inout Set - ) throws -> [String: AntigravityBundle] { + in file: URL, base: URL, depth: Int, traversal: inout AntigravityDiscoveryTraversal + ) throws -> AntigravityDiscoveries { guard depth < 16 else { throw CoreError.invalidState("plugin discovery inheritance is too deep") } - guard visited.insert(file.resolvingSymlinksInPath().path).inserted, - let manifest = try HostPluginDocuments.read(file) - else { return [:] } + let filePath = file.resolvingSymlinksInPath().path + let key = [filePath, base.path] + if let cached = traversal.read[key] { return cached } + guard traversal.active.insert(filePath).inserted else { return .init() } + defer { traversal.active.remove(filePath) } + guard let manifest = try HostPluginDocuments.read(file) else { + traversal.read[key] = .init() + return .init() + } func resolved(_ text: String) -> URL { text.hasPrefix("/") ? URL(fileURLWithPath: text).standardizedFileURL : base.appendingPathComponent(text).standardizedFileURL } - var result: [String: AntigravityBundle] = [:] + var result = AntigravityDiscoveries( + ownExclusions: try HostPluginDocuments.strings(manifest.hostValue(["exclude"]))) for key in ["entries", "inherits"] { for entry in try HostPluginDocuments.list(manifest.hostValue([key])) { let fields = try HostPluginDocuments.fields(entry) @@ -270,21 +353,24 @@ struct HostPluginLocations { let parent = source.deletingLastPathComponent() let root = parent.lastPathComponent == ".agents" ? parent.deletingLastPathComponent() : parent - candidates = try antigravityEntries( - in: source, base: root, depth: depth + 1, visited: &visited) + let inherited = try antigravityEntries( + in: source, base: root, depth: depth + 1, traversal: &traversal) + candidates = inherited.bundles + result.inheritedExclusions.formUnion(inherited.exclusions) } else if let bundle = try antigravityBundle(at: source) { candidates = [source.lastPathComponent: bundle] } else { candidates = try antigravityBundles(at: source) } for (id, bundle) in candidates - where result[id] == nil + where result.bundles[id] == nil && (include.isEmpty || include.contains(id)) && !exclude.contains(id) { - result[id] = bundle + result.bundles[id] = bundle } } } + traversal.read[key] = result return result } } diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift index 8e471a5..964afc4 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift @@ -2,20 +2,19 @@ import AgentsCore import AgentsManifest import Foundation -struct HostPluginTarget { - let declaration: HostPluginDeclaration +struct HostPluginTarget: Sendable { + let name: String + let selector: HostPluginSelector? + let enabled: Bool? let agent: AgentID let scope: InstallScope + let claudeScope: ClaudePluginScope? let id: String? let bundle: URL? let marketplaceName: String? let marketplaceSource: String? - let issue: (HostPluginDrift, String)? - - var claudeScope: ClaudePluginScope? { - guard agent == .claudeCode else { return nil } - return declaration.claudeScope ?? (scope == .user ? .user : .project) - } + var issue: (HostPluginDrift, String)? + var manifestDisabled = false static let supportedAgents: Set = [.codex, .claudeCode, .antigravity] @@ -26,42 +25,137 @@ struct HostPluginTarget { let declaration = try store.loadDeclaration() let recipients = Set(agents ?? AgentID.allCases) let root = scope == .user ? store.directory : environment.projectDirectory - let groups = Dictionary(uniqueKeysWithValues: declaration.groups.map { ($0.name, $0) }) #if os(macOS) let platform = DeclarationPlatform.macOS #else let platform = DeclarationPlatform.linux #endif + struct Context { + let root: URL + let declaration: Declaration + let groups: [String: ComponentGroupDeclaration] + + init(root: URL, declaration: Declaration) { + self.root = root + self.declaration = declaration + groups = Dictionary(uniqueKeysWithValues: declaration.groups.map { ($0.name, $0) }) + } + } var targets: [Self] = [] - var seenGroups = Set() + var seenGroups = Set<[String]>() + var producers: [String: Context] = [:] func permits(_ condition: DeclarationCondition?, agent: AgentID) -> Bool { (condition?.agents?.contains(agent) ?? true) && (condition?.scopes?.contains(scope) ?? true) && (condition?.platforms?.contains(platform) ?? true) } - func add(_ components: [ComponentDeclaration], agents selected: Set) { + func add( + _ components: [ComponentDeclaration], in context: Context, agents selected: Set + ) { for component in components { guard case .hostPlugin(let plugin) = component else { continue } for agent in plugin.agents where selected.contains(agent) { targets.append( resolve( - plugin, agent: agent, scope: scope, root: root, sources: declaration.sources, - environment: environment)) + plugin, agent: agent, scope: scope, root: context.root, + sources: context.declaration.sources, environment: environment)) } } } - func visit(_ use: GroupUseDeclaration, agents selected: Set) { - guard use.source == nil || use.source == ".", let group = groups[use.name] else { return } - let allowed = selected.filter { agent in - permits(use.condition, agent: agent) && permits(group.condition, agent: agent) - && seenGroups.insert(group.name + "\0" + agent.rawValue).inserted + func producer(_ alias: String, from context: Context) throws -> Context { + guard let source = context.declaration.sources[alias], source.kind == .local, + source.requirement == nil + else { throw CoreError.unsupported("Host plugin exports require a readable local source.") } + let origin = source.localURL(environment: environment).resolvingSymlinksInPath() + let root = try PathSafety.resolvedChild(base: origin, subpath: source.path ?? ".") + .resolvingSymlinksInPath() + let file = root.appendingPathComponent( + root.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml") + guard PathSafety.isContained(file.resolvingSymlinksInPath(), in: origin) else { + throw CoreError.unsafePath("Host plugin export escapes its source.") + } + if let cached = producers[root.path] { return cached } + guard producers.count < 256, + let data = try TargetPrecondition.readingFile( + file, maximumFileBytes: ManifestLimits.Input.bytes + ).bytes + else { throw CoreError.unsupported("Host plugin export declaration is unavailable.") } + let document = try DeclarationDocument(bytes: Array(data), identity: .init(file.path)) + var producerEnvironment = environment + producerEnvironment.projectDirectory = root + let loaded = try ManifestProjection.declaration( + of: document, environment: producerEnvironment) + let result = Context(root: root, declaration: loaded) + producers[root.path] = result + return result + } + func visit( + _ use: GroupUseDeclaration, in context: Context, agents selected: Set, depth: Int + ) { + let active = selected.filter { permits(use.condition, agent: $0) } + guard !active.isEmpty else { return } + let owner: Context? + if depth >= 64 { + owner = nil + } else if let alias = use.source, alias != "." { + if let exported = try? producer(alias, from: context), + exported.declaration.exports.contains(use.name) + { + owner = exported + } else { + owner = nil + } + } else { + owner = context + } + guard let owner else { + // An active reference may name a remote, pinned, or unreadable producer. + let label = (use.source.map { $0 + ":" } ?? "") + use.name + for agent in AgentID.allCases + where active.contains(agent) && supportedAgents.contains(agent) { + targets.append( + .init( + name: label, selector: nil, enabled: nil, agent: agent, scope: scope, + claudeScope: nil, id: nil, bundle: nil, marketplaceName: nil, + marketplaceSource: nil, + issue: ( + .unsupported, + "Host plugins could not be inspected in group '\(label)'. Use a readable local exported group." + ))) + } + return + } + guard let group = owner.groups[use.name] else { return } + let allowed = active.filter { agent in + permits(group.condition, agent: agent) + && seenGroups.insert([ + owner.root.resolvingSymlinksInPath().path, group.name, agent.rawValue, + ]) + .inserted } guard !allowed.isEmpty else { return } - add(group.components, agents: allowed) - for nested in group.uses { visit(nested, agents: allowed) } + add(group.components, in: owner, agents: allowed) + for nested in group.uses { visit(nested, in: owner, agents: allowed, depth: depth + 1) } + } + let context = Context(root: root, declaration: declaration) + add(declaration.components, in: context, agents: recipients) + for use in declaration.uses { visit(use, in: context, agents: recipients, depth: 0) } + + var byPlugin: [[String]: [Int]] = [:] + for index in targets.indices { + let target = targets[index] + guard target.issue == nil, let id = target.id else { continue } + let key = [target.agent.rawValue, target.claudeScope?.rawValue ?? target.scope.rawValue, id] + byPlugin[key, default: []].append(index) + } + for indexes in byPlugin.values + where Set(indexes.compactMap { targets[$0].enabled }).count > 1 { + for index in indexes { + targets[index].issue = ( + .unsupported, "Host plugin declarations specify conflicting enabled states." + ) + } } - add(declaration.components, agents: recipients) - for use in declaration.uses { visit(use, agents: recipients) } return targets } @@ -69,13 +163,18 @@ struct HostPluginTarget { _ declaration: HostPluginDeclaration, agent: AgentID, scope: InstallScope, root: URL, sources: [String: SourceDeclaration], environment: RuntimeEnvironment ) -> Self { + let claudeScope: ClaudePluginScope? = + agent == .claudeCode ? declaration.claudeScope ?? (scope == .user ? .user : .project) : nil func target( id: String? = nil, bundle: URL? = nil, marketplaceName: String? = nil, - marketplaceSource: String? = nil, issue: (HostPluginDrift, String)? = nil + marketplaceSource: String? = nil, issue: (HostPluginDrift, String)? = nil, + manifestDisabled: Bool = false ) -> Self { .init( - declaration: declaration, agent: agent, scope: scope, id: id, bundle: bundle, - marketplaceName: marketplaceName, marketplaceSource: marketplaceSource, issue: issue) + name: declaration.name, selector: declaration.selector, enabled: declaration.enabled, + agent: agent, scope: scope, claudeScope: claudeScope, id: id, bundle: bundle, + marketplaceName: marketplaceName, marketplaceSource: marketplaceSource, issue: issue, + manifestDisabled: manifestDisabled) } guard supportedAgents.contains(agent) else { return target(issue: (.unsupported, "This agent has no host plugin sync adapter.")) @@ -125,7 +224,7 @@ struct HostPluginTarget { return target(issue: (.unverified, "The contained plugin bundle could not be read.")) } if agent == .antigravity { - guard try HostPluginLocations.antigravityManifest(at: bundle) != nil else { + guard let manifest = try HostPluginLocations.antigravityManifest(at: bundle) else { return target(issue: (.unsupported, "The bundle has no Antigravity plugin manifest.")) } let id = bundle.lastPathComponent @@ -133,7 +232,8 @@ struct HostPluginTarget { return target( issue: (.unsupported, "The Antigravity plugin directory has an invalid name.")) } - return target(id: id, bundle: bundle) + let disabled = try HostPluginDocuments.boolean(manifest.hostValue(["disabled"])) ?? false + return target(id: id, bundle: bundle, manifestDisabled: disabled) } let manifest = agent == .codex diff --git a/Sources/AgentsUpdates/HostPlugins/SkillGovernance.swift b/Sources/AgentsUpdates/HostPlugins/SkillGovernance.swift index 735ff34..0d84de3 100644 --- a/Sources/AgentsUpdates/HostPlugins/SkillGovernance.swift +++ b/Sources/AgentsUpdates/HostPlugins/SkillGovernance.swift @@ -159,7 +159,10 @@ public enum SkillGovernance { let opaqueClaudeRoot: Bool func name(for agent: AgentID) -> String { - agent == .antigravity ? namespace + ":" + content.skill.name : content.skill.name + if agent == .antigravity || agent == .claudeCode { + return namespace + ":" + content.skill.name + } + return content.skill.name } } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 1a65ba7..8466d70 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -222,7 +222,16 @@ final class UpdatePlan { request.selectedIdentities = try MarketplaceGraphChange.deploymentIdentities( from: previous, to: next, roots: roots) } else { - next = DeploymentConstruction.retargetLegacyCodexSkills(previous, scope: store.scope) + let names = Set(request.names) + next = try DeploymentConstruction.retargetLegacyCodexSkills(previous, scope: store.scope) { + deployment in + try deployment.owners.contains { owner in + try ArtifactAggregation.selects( + owner, in: previous, roots: roots, kinds: request.kinds, names: names, + identities: request.selectedIdentities, retargetedInstructions: retargetedInstructions + ) + } + } } try MarketplaceGraphChange.validateHosted( next.marketplaceGraph, objects: next.contentObjects, policy: sourcePolicy.effective, diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index bf5b163..b603d83 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -613,19 +613,28 @@ package final class ArtifactAggregation: PreparedEvidence { } private func isSelected(_ id: String, in selected: ResolvedLedger) throws -> Bool { + try Self.selects( + id, in: selected, roots: roots, kinds: selectedKinds, names: selectedNames, + identities: selectedIdentities, retargetedInstructions: retargetedInstructions) + } + + package static func selects( + _ id: String, in selected: ResolvedLedger, roots: [String: URL], + kinds: Set?, names: Set, identities: Set?, + retargetedInstructions: Set + ) throws -> Bool { guard let c = selected.components[id] else { return false } if try retargetedInstructions.contains( LedgerImpact.identity(c, ledger: selected, roots: roots)) { return true } - if let selectedIdentities { - return try selectedIdentities.contains( - LedgerImpact.identity(c, ledger: selected, roots: roots)) + if let identities { + return try identities.contains(LedgerImpact.identity(c, ledger: selected, roots: roots)) } - return (selectedKinds?.contains(DeclaredComponentKind(rawValue: c.kind)!) ?? true) - && (selectedNames.isEmpty - || selectedNames.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) + return (kinds?.contains(DeclaredComponentKind(rawValue: c.kind)!) ?? true) + && (names.isEmpty + || names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) } private struct ComponentOutputEntry { diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift index 7119881..17c5c57 100644 --- a/Sources/Components/DeploymentConstruction.swift +++ b/Sources/Components/DeploymentConstruction.swift @@ -4,14 +4,16 @@ import Foundation package enum DeploymentConstruction { package static func retargetLegacyCodexSkills( - _ previous: ResolvedLedger, scope: InstallScope - ) -> ResolvedLedger { + _ previous: ResolvedLedger, scope: InstallScope, + selecting: (LedgerDeployment) throws -> Bool + ) throws -> ResolvedLedger { guard scope == .user else { return previous } var next = previous for index in next.deployments.indices { let deployment = next.deployments[index] if deployment.route == "agents/skill@1", deployment.target.kind == .registered, - deployment.target.root == "skills-codex", deployment.recipients == [.codex] + deployment.target.root == "skills-codex", deployment.recipients == [.codex], + try selecting(deployment) { next.deployments[index].target.root = AgentRegistry.skillRootKey(for: .codex, scope: scope) next.deployments[index].target.path = PathSafety.sanitizeName(deployment.target.path) @@ -252,6 +254,9 @@ package enum DeploymentConstruction { platform: DeclarationPlatform ) throws -> ResolvedLedger { var ledger = frozen.ledger + func portable(_ component: LinkedComponent) -> Bool { + component.origins.first?.pluginExpansion?.input.format == "native/agentPluginV1@1" + } 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 })? @@ -261,6 +266,9 @@ package enum DeploymentConstruction { else { continue } _ = record for agent in parent.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + if portable(parent), !NativeGeneratedPluginLayoutV1.supports(surface(agent), scope: scope) { + continue + } ledger.lowerings.append( try NativeGeneratedPluginLayoutV1.lower( parent, members: linked.components, frozen: frozen, @@ -272,11 +280,12 @@ package enum DeploymentConstruction { 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 - }) + portable(original) + || ledger.lowerings.contains(where: { + $0.format.hasSuffix("-generated-plugin@1") + && $0.layout.object?["occurrences"]?.array?.contains( + .init(integer: original.origins[0].occurrence)) == true + }) { continue } diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index 2740645..d7d5890 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -550,7 +550,9 @@ final class Expansion { condition: effective, recipients: effective.recipients( requested: overrides[name]?.agents ?? selection.agents - ?? context.declaration.defaultAgents, + ?? (pluginFrame?.input.format == "native/agentPluginV1@1" + ? pluginFrame?.recipients.sorted { $0.rawValue < $1.rawValue } : nil) + ?? context.declaration.defaultAgents, scope: linking.store.scope, platform: linking.platform), chatGPT: false, resources: [resource], chain: chain, position: position, dependencies: dependencies + [view.snapshot]) diff --git a/Sources/Components/Import/ImportInput.swift b/Sources/Components/Import/ImportInput.swift index 6ec8906..fa8df7f 100644 --- a/Sources/Components/Import/ImportInput.swift +++ b/Sources/Components/Import/ImportInput.swift @@ -22,23 +22,22 @@ enum ImportInput { } static func bytes(_ input: SourceImportInput, limits: SourceImportLimits) throws -> Data { + let view = try snapshot(input.root) + guard let bytes = try optionalBytes(in: view, document: input.document, limits: limits) else { + throw ImportReadFailure.invalid + } + return bytes + } + + static func optionalBytes( + in view: SourceSnapshot, document: String, 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 + return try TargetPrecondition.readingFile( + view.resource(document), maximumFileBytes: limits.documentBytes + ).bytes } static func snapshot(_ root: URL) throws -> SourceSnapshot { diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift index f7d577f..6876870 100644 --- a/Sources/Components/Import/NativeContainerImport.swift +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -485,7 +485,9 @@ enum NativeContainerImport { source: "native-input", .init( select: .names([content.skill.name]), path: preservationPath, - agents: [NativeImportInput.agent(input.profile)], condition: content.skill.condition)), + agents: input.profile == .agentPluginV1 + ? nil : [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) diff --git a/Sources/Components/NativeGeneratedPluginLayoutV1.swift b/Sources/Components/NativeGeneratedPluginLayoutV1.swift index d1ad111..f2a4fd4 100644 --- a/Sources/Components/NativeGeneratedPluginLayoutV1.swift +++ b/Sources/Components/NativeGeneratedPluginLayoutV1.swift @@ -126,18 +126,29 @@ package enum NativeGeneratedPluginLayoutV1 { ]), platform: platform.rawValue, artifacts: []) } - static func recipe(_ input: ComponentRenderInput) throws -> (NativeComponentRoute, String) { - switch input.request.surface { + static func supports(_ surface: NativeClientSurface, scope: InstallScope) -> Bool { + container(surface, scope: scope) != nil + } + + private static func container(_ surface: NativeClientSurface, scope: InstallScope) + -> (NativeComponentRoute, String)? + { + switch surface { case .claudeCode: return (.claudeSkillPlugin, ".claude-plugin/plugin.json") - case .cursorEditor where input.request.scope == .user: + case .cursorEditor where scope == .user: return (.cursorLocalPlugin, ".cursor-plugin/plugin.json") - case .geminiCLI where input.request.scope == .user: - return (.geminiExtension, "gemini-extension.json") - default: + case .geminiCLI where scope == .user: return (.geminiExtension, "gemini-extension.json") + default: return nil + } + } + + static func recipe(_ input: ComponentRenderInput) throws -> (NativeComponentRoute, String) { + guard let recipe = container(input.request.surface, scope: input.request.scope) else { throw input.issue( ["scope"], .unverified, "generated native container registration is not established for this surface/scope") } + return recipe } static func selectedChildren(_ input: ComponentRenderInput, platform: String) throws diff --git a/Sources/Components/PluginExpansion.swift b/Sources/Components/PluginExpansion.swift index d47cfff..c51ab81 100644 --- a/Sources/Components/PluginExpansion.swift +++ b/Sources/Components/PluginExpansion.swift @@ -258,12 +258,19 @@ enum PluginManifestSelection { in view: SourceSnapshot, container: String ) throws -> [(SourceImportProfile, String)] { func path(_ suffix: String) -> String { container == "." ? suffix : container + "/" + suffix } - func document(_ relative: String) throws -> NativeDocument? { - guard let bytes = try FileSystem.readUnlessDenied(at: view.resource(relative)) else { + let limits = SourceImportLimits() + let budget = try NativeImportBudget(limits) + func document(_ relative: String, ignoringMalformed: Bool = false) throws -> NativeDocument? { + guard let bytes = try ImportInput.optionalBytes(in: view, document: relative, limits: limits) + else { + return nil + } + try budget.document(bytes, path: relative) + do { + return try NativeDocument(bytes: bytes, format: .json, budget: budget.parser) + } catch NativeDocumentError.invalidDocument where ignoringMalformed { return nil } - return try NativeDocument( - bytes: bytes, format: .json, budget: NativeImportBudget(.init()).parser) } let claude = path(".claude-plugin/plugin.json") let portable = path("plugin.json") @@ -278,7 +285,7 @@ enum PluginManifestSelection { entries.append((profile, relative)) } } - if let root = try? document(portable), + if let root = try document(portable, ignoringMalformed: true), try root.read(.init(keys: ["$schema"]))?.value == .string(AgentPluginManifest.schema) { if entries.contains(where: { $0.0 == .claudePluginV1 }) { diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index d37cf7d..0c5b90e 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -987,3 +987,73 @@ extension StateTransactionTests { #expect(try Data(contentsOf: config) == concurrent + toggle) } } + +extension StateTransactionTests { + @Test func hostTogglePreservesInPlaceEditsAfterExchange() throws { + let fixture = try TransactionFixture() + let store = fixture.store + let config = fixture.root.appendingPathComponent(".codex/config.toml") + try FileManager.default.createDirectory( + at: config.deletingLastPathComponent(), withIntermediateDirectories: true) + let original = Data("model = 'first'\n".utf8) + let concurrent = Data("model = 'concurrent'\n".utf8) + let displaced = Data("model = 'also concurrent'\n".utf8) + try original.write(to: config) + let originalHandle = try FileHandle(forUpdating: config) + defer { try? originalHandle.close() } + var exchanged = false + #expect(throws: (any Error).self) { + try HostPluginConfigurationRoute.codex.edit( + store: store, maximumFileBytes: 4096, + checkpoint: { point in + guard point == TransactionCheckpoint.publication(0, .exchanged).name else { return } + exchanged = true + let current = try FileHandle(forWritingTo: config) + defer { try? current.close() } + try current.truncate(atOffset: 0) + try current.write(contentsOf: concurrent) + try originalHandle.truncate(atOffset: 0) + try originalHandle.write(contentsOf: displaced) + }, + transform: { _ in Data("[plugins.'demo@test']\nenabled = false\n".utf8) }) + } + #expect(exchanged) + #expect(try Data(contentsOf: config) == concurrent) + let diagnostic = FileTransaction.recoveryDiagnostic(store: store) + #expect(diagnostic.requiresOwner) + #expect(throws: CoreError.recoveryPending(diagnostic.message)) { try store.loadLedger() } + #expect(throws: CoreError.self) { try store.withLock {} } + #expect(try Data(contentsOf: config) == concurrent) + try originalHandle.seek(toOffset: 0) + #expect(try originalHandle.readToEnd() == displaced) + let files = try #require( + FileManager.default.enumerator( + at: fixture.root, includingPropertiesForKeys: [.isRegularFileKey])) + #expect(files.compactMap { $0 as? URL }.contains { (try? Data(contentsOf: $0)) == displaced }) + } + + @Test func interruptedHostToggleRestoresDisplacedSettingsFromJournal() throws { + let fixture = try TransactionFixture() + let store = fixture.store + let config = fixture.root.appendingPathComponent(".codex/config.toml") + try FileManager.default.createDirectory( + at: config.deletingLastPathComponent(), withIntermediateDirectories: true) + let original = Data("model = 'first'\n".utf8) + try original.write(to: config) + let child = try stateTestProcess( + root: fixture.root, + arguments: ["host-toggle-publication", TransactionCheckpoint.publication(0, .exchanged).name]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + try ProcessWait.stopped(child, root: fixture.root) + #expect(try Data(contentsOf: config) != original) + terminateProcess(child) + #expect(throws: pendingRecovery) { try store.loadLedger() } + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + #expect(try Data(contentsOf: config) == original) + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path)) + } +} diff --git a/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift b/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift index b3efef3..66b27bc 100644 --- a/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift +++ b/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsInstructions import AgentsManifest import AgentsSkills import AgentsUpdates @@ -62,6 +63,40 @@ struct CodexUserIsolationTests { } } + @Test func instructionOnlyRestorePreservesLegacySkillOwnership() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "managed") + let instructions = fixture.repo.appendingPathComponent("instructions") + try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) + try Data("---\ndescription: Rules\n---\n\n# Rules\n\nRestored rules\n".utf8) + .write(to: instructions.appendingPathComponent("rules.md")) + try fixture.commit() + _ = try fixture.add(mode: .copy, scope: .user) + _ = try InstructionOperations.add( + InstructionAddOptions( + source: fixture.repo.path, names: ["rules"], agents: [.codex], scope: .user, + environment: fixture.environment)) + let instructionTarget = fixture.environment.homeDirectory.appendingPathComponent( + ".codex/AGENTS.md") + try FileManager.default.removeItem(at: instructionTarget) + let (privateSkill, sharedSkill) = try seedLegacy(fixture) + try FileManager.default.createDirectory(at: privateSkill, withIntermediateDirectories: true) + try Data("unmanaged private".utf8).write(to: privateSkill.appendingPathComponent("SKILL.md")) + + _ = try InstructionOperations.installResolvedReport( + scope: .user, environment: fixture.environment) + let ledger = try fixture.store(.user).loadLedger() + #expect( + ledger.deployments.first { $0.route == "agents/skill@1" }?.target.root == "skills-codex") + #expect(try String(contentsOf: instructionTarget, encoding: .utf8).contains("Restored rules")) + #expect(try fixture.body(sharedSkill).contains("managed")) + try SkillOperations.remove( + skillNames: ["demo"], scope: .user, agents: [.codex], environment: fixture.environment) + + #expect(try fixture.body(privateSkill) == "unmanaged private") + #expect(!FileManager.default.fileExists(atPath: sharedSkill.path)) + } + @Test func migrationKeepsCursorOwnedSharedLeafAndWarnsOnlyAboutUnmanagedLinks() throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "shared") @@ -133,7 +168,8 @@ struct CodexUserIsolationTests { } let store = fixture.store(.user) var ledger = try store.loadLedger() - let index = try #require(ledger.deployments.firstIndex { $0.recipients == [.codex] }) + let index = try #require( + ledger.deployments.firstIndex { $0.route == "agents/skill@1" && $0.recipients == [.codex] }) ledger.deployments[index].target.root = "skills-codex" try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) return (privateSkill, sharedSkill) diff --git a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift index 59212c4..add6fce 100644 --- a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift +++ b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift @@ -312,3 +312,355 @@ final class HostPluginFixture: Sendable { at: path.appendingPathComponent("SKILL.md")) } } + +extension HostPluginExecutorTests { + @Test func projectCodexSymlinkCannotToggleUserSettings() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, enabled: false, agents: [codex]} + """) + let userConfig = fixture.home.appendingPathComponent(".codex/config.toml") + try fixture.write(#"[plugins."github@curated"]"# + "\nenabled = true\n", at: userConfig) + try fixture.codexBundle("curated/github/1") + try FileManager.default.createSymbolicLink( + at: fixture.project.appendingPathComponent(".codex"), + withDestinationURL: userConfig.deletingLastPathComponent()) + let before = try Data(contentsOf: userConfig) + let preview = try HostPluginExecutor.preview(environment: fixture.environment) + #expect(preview.first?.status.drift == .unsupported) + #expect(preview.first?.configurationChanges.isEmpty == true) + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + #expect(result.first?.outcome == .unsupported) + #expect(result.first?.diagnostic?.contains("project authority") == true) + #expect(await runner.calls.isEmpty) + #expect(try Data(contentsOf: userConfig) == before) + } + + @Test(arguments: [AgentID.codex, .claudeCode]) + func rejectsForeignMarketplaceAndUsesVerifiedBundleOrigin(_ agent: AgentID) async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + sources: {pack: {path: ./pack}} + components: + - {kind: hostPlugin, name: review, source: pack, path: review, agents: [\(agent.rawValue)]} + """) + let pack = fixture.project.appendingPathComponent("pack") + let foreign = fixture.project.appendingPathComponent("unrelated") + try FileManager.default.createDirectory(at: foreign, withIntermediateDirectories: true) + try fixture.write( + #"{"name":"work","plugins":[{"name":"review","source":"./review"}]}"#, + at: pack.appendingPathComponent( + agent == .codex ? ".agents/plugins/marketplace.json" : ".claude-plugin/marketplace.json")) + try fixture.write( + #"{"name":"review"}"#, at: pack.appendingPathComponent("review/plugin.json")) + let registration = fixture.home.appendingPathComponent( + agent == .codex ? ".codex/config.toml" : ".claude/plugins/known_marketplaces.json") + func registrationText(_ path: URL) -> String { + agent == .codex + ? "[marketplaces.work]\nsource_type = 'local'\nsource = '\(path.path)'\n" + : #"{"work":{"source":{"source":"directory","path":"\#(path.path)"}}}"# + } + let foreignRegistration = registrationText(foreign) + try fixture.write(foreignRegistration, at: registration) + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + #expect(result.first?.outcome == .unsupported) + #expect(result.first?.diagnostic?.contains("provenance") == true) + #expect(await runner.calls.isEmpty) + + let alias = fixture.project.appendingPathComponent("same-producer") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: pack) + try fixture.write(registrationText(alias), at: registration) + let preview = try HostPluginExecutor.preview(environment: fixture.environment) + let host = agent == .codex ? "codex" : "claude" + #expect(preview.first?.status.drift == .missing) + #expect( + preview.first?.commands.first?.prefix(3) == [ + host, "plugin", agent == .codex ? "add" : "install", + ]) + + try FileManager.default.removeItem(at: registration) + let add = [host, "plugin", "marketplace", "add", pack.path] + let registrationRunner = RecordingHostRunner { argv, _ in + guard argv == add else { return .failed } + do { + try fixture.write(foreignRegistration, at: registration) + return .success + } catch { return .failed } + } + let readback = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: registrationRunner) + #expect(readback.first?.outcome == .unsupported) + #expect(await registrationRunner.calls == [add]) + } + + @Test func claudeDetectsForeignMarketplaceDeclaredInProjectSettings() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: review, pluginId: review@work, marketplace: https://github.com/team/work.git, agents: [claude-code]} + """, scope: .user) + try fixture.write( + #"{"work":{"source":{"source":"github","repo":"team/work"}}}"#, + at: fixture.home.appendingPathComponent(".claude/plugins/known_marketplaces.json")) + try fixture.write( + #"{"extraKnownMarketplaces":{"work":{"source":{"source":"github","repo":"other/work"}}}}"#, + at: fixture.project.appendingPathComponent(".claude/settings.json")) + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(result.first?.outcome == .unsupported) + #expect(result.first?.diagnostic?.contains("provenance") == true) + #expect(await runner.calls.isEmpty) + } + + @Test(arguments: [false, true]) + func codexDetectsForeignDiscoveredMarketplaceDuringUserSync(_ personal: Bool) async throws { + let fixture = try HostPluginFixture() + let bundle = fixture.project.appendingPathComponent("pack/review") + let catalog = #"{"name":"work","plugins":[{"name":"review","source":"./review"}]}"# + try fixture.write( + catalog, at: fixture.project.appendingPathComponent("pack/.agents/plugins/marketplace.json")) + try fixture.write(#"{"name":"review"}"#, at: bundle.appendingPathComponent("plugin.json")) + let root = personal ? fixture.home : fixture.project + try fixture.write(catalog, at: root.appendingPathComponent(".agents/plugins/marketplace.json")) + try fixture.declare( + """ + sources: {pack: {path: "\(bundle.deletingLastPathComponent().path)"}} + components: + - {kind: hostPlugin, name: review, source: pack, path: review, agents: [codex]} + """, scope: .user) + + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(result.first?.outcome == .unsupported) + #expect(result.first?.diagnostic?.contains("provenance") == true) + #expect(await runner.calls.isEmpty) + } + + @Test func antigravityProjectBundleRequiresTheDeclaredPhysicalPath() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: review, source: ".", path: wanted/review, agents: [antigravity]} + """) + let wanted = fixture.project.appendingPathComponent("wanted/review") + let wrong = fixture.project.appendingPathComponent("wrong/review") + for bundle in [wanted, wrong] { + try fixture.write(#"{"name":"review"}"#, at: bundle.appendingPathComponent("plugin.json")) + } + let registry = fixture.project.appendingPathComponent(".agents/plugins.json") + let foreign = #"{"entries":[{"path":"wrong/review"}]}"# + try fixture.write(foreign, at: registry) + let runner = RecordingHostRunner { _, _ in .failed } + let blocked = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + #expect(blocked.first?.outcome == .unsupported) + #expect(try String(contentsOf: registry, encoding: .utf8) == foreign) + + let alias = fixture.project.appendingPathComponent("alias") + try FileManager.default.createDirectory(at: alias, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: alias.appendingPathComponent("review"), withDestinationURL: wanted) + try fixture.write(#"{"entries":[{"path":"alias/review"}]}"#, at: registry) + let verified = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + #expect(verified.first?.outcome == .unchanged) + #expect(await runner.calls.isEmpty) + } + + @Test func resolvesActiveLocalExportedHostPlugins() throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + sources: {pack: {path: ./pack}} + uses: + - {group: active, source: pack} + - {group: inactive, source: pack, condition: {scopes: [user]}} + """) + try fixture.write( + """ + version: 1 + exports: [active, inactive] + groups: + active: + components: + - {kind: hostPlugin, name: local-review, source: ".", path: review, agents: [antigravity]} + inactive: + components: + - {kind: hostPlugin, name: inactive-review, pluginId: inactive, agents: [antigravity]} + """, + at: fixture.project.appendingPathComponent("pack/.agent/agents.yaml")) + try fixture.write( + #"{"name":"review"}"#, at: fixture.project.appendingPathComponent("pack/review/plugin.json")) + let preview = try HostPluginExecutor.preview( + agents: [.antigravity], environment: fixture.environment) + #expect(preview.map(\.status.name) == ["local-review"]) + #expect(preview.first?.configurationChanges.first?.after == .appendPath("pack/review")) + #expect( + try HostPluginExecutor.preview( + agents: [.codex], environment: fixture.environment + ).isEmpty) + } + + @Test func unavailableActiveExportIsReportedWithoutRunningCommands() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + sources: {remote: {url: https://example.invalid/pack.git}} + uses: [{source: remote, group: exported, condition: {agents: [codex]}}] + """) + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + #expect(result.map(\.status.name) == ["remote:exported"]) + #expect(result.first?.status.pluginId == nil) + #expect(result.first?.status.desiredEnabled == nil) + #expect(result.first?.outcome == .unsupported) + #expect(await runner.calls.isEmpty) + } + + @Test func conflictingDeclarationsAreRejectedBeforeHostMutation() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: first, pluginId: review@work, agents: [claude-code]} + - {kind: hostPlugin, name: second, pluginId: review@work, agents: [claude-code], enabled: false, claudeScope: project} + """) + let before = try FileHash.folderHash(fixture.root) + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + #expect(result.map(\.outcome) == [.unsupported, .unsupported]) + #expect(result.allSatisfy { $0.diagnostic?.contains("conflicting enabled states") == true }) + #expect(await runner.calls.isEmpty) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func antigravityDisabledSourceDoesNotWriteProjectRegistry() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: review, source: ".", path: bundles/review, agents: [antigravity]} + """) + try fixture.write( + #"{"name":"review","disabled":true}"#, + at: fixture.project.appendingPathComponent("bundles/review/plugin.json")) + let runner = RecordingHostRunner { _, _ in .failed } + let preview = try HostPluginExecutor.preview(environment: fixture.environment) + #expect(preview.first?.status.drift == .unsupported) + #expect(preview.first?.configurationChanges.isEmpty == true) + let result = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + #expect(result.first?.outcome == .unsupported) + #expect(await runner.calls.isEmpty) + #expect( + !FileManager.default.fileExists( + atPath: fixture.project.appendingPathComponent(".agents/plugins.json").path)) + } + + @Test func antigravityProjectShadowOfDisabledGlobalPluginAgreesWithDoctor() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: review, source: ".", path: .agents/plugins/review, agents: [antigravity]} + """) + let local = fixture.project.appendingPathComponent(".agents/plugins/review") + try fixture.write(#"{"name":"local"}"#, at: local.appendingPathComponent("plugin.json")) + try fixture.skill( + path: local.appendingPathComponent("skills/check"), name: "check", description: "Local") + try fixture.write( + #"{"name":"global","disabled":true}"#, + at: fixture.home.appendingPathComponent(".gemini/config/plugins/review/plugin.json")) + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + let report = try SkillGovernance.inspect( + agents: [.antigravity], environment: fixture.environment) + #expect(result.first?.outcome == .unsupported) + #expect(result.first?.status == report.hostPlugins.first) + #expect(result.first?.status.effectiveEnabled == false) + #expect(report.skillBudgets == nil) + #expect(await runner.calls.isEmpty) + } + + @Test func cancellationRetainsCompletedResultsAndReconcilesTheInFlightCommand() async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: first, pluginId: existing@work, agents: [claude-code]} + - {kind: hostPlugin, name: running, pluginId: second@work, agents: [codex]} + - {kind: hostPlugin, name: unstarted, pluginId: third@work, agents: [codex]} + """, scope: .user) + let first = fixture.home.appendingPathComponent(".claude/plugins/cache/existing") + try fixture.write( + #"{"name":"existing"}"#, at: first.appendingPathComponent(".claude-plugin/plugin.json")) + try fixture.write( + #"{"plugins":{"existing@work":[{"scope":"user","installPath":"\#(first.path)"}]}}"#, + at: fixture.home.appendingPathComponent(".claude/plugins/installed_plugins.json")) + let runner = CancellationHostRunner(fixture: fixture) + let task = Task { + try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + } + await runner.waitForCommand() + task.cancel() + await runner.finishCommand() + let result = try await task.value + #expect(result.map(\.status.name) == ["first", "running"]) + #expect(result.map(\.outcome) == [.unchanged, .failed]) + #expect(result.last?.status.installed == true) + #expect(result.last?.diagnostic?.contains("cancelled") == true) + #expect(await runner.calls == [["codex", "plugin", "add", "second@work", "--json"]]) + } +} + +private actor CancellationHostRunner: HostPluginCommandRunner { + let fixture: HostPluginFixture + private(set) var calls: [[String]] = [] + private var started: CheckedContinuation? + private var release: CheckedContinuation? + + init(fixture: HostPluginFixture) { self.fixture = fixture } + + func waitForCommand() async { + guard calls.isEmpty else { return } + await withCheckedContinuation { started = $0 } + } + + func finishCommand() { + release?.resume() + release = nil + } + + func run(argv: [String], environment: RuntimeEnvironment) async -> HostPluginCommandResult { + calls.append(argv) + if calls.count == 1 { + await withCheckedContinuation { + release = $0 + started?.resume() + started = nil + } + } + do { + try fixture.codexBundle("work/second/1") + try fixture.write( + #"[plugins."second@work"]"# + "\nenabled = true\n", + at: fixture.home.appendingPathComponent(".codex/config.toml")) + return .success + } catch { return .failed } + } +} diff --git a/Tests/AgentsUpdatesTests/PortablePluginDeploymentTests.swift b/Tests/AgentsUpdatesTests/PortablePluginDeploymentTests.swift new file mode 100644 index 0000000..1682d85 --- /dev/null +++ b/Tests/AgentsUpdatesTests/PortablePluginDeploymentTests.swift @@ -0,0 +1,34 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +struct PortablePluginDeploymentTests { + @Test func portablePluginSkillsDeployAndRestoreForCodexOnly() throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: plugin, name: portable, source: ".", path: bundle, agents: [codex]} + """) + let bundle = fixture.project.appendingPathComponent("bundle") + try fixture.write( + #"{"$schema":"\#(AgentPluginManifest.schema)","name":"portable"}"#, + at: bundle.appendingPathComponent("plugin.json")) + try fixture.skill( + path: bundle.appendingPathComponent("skills/review"), + name: "review", description: "Portable review") + + _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { try $0.apply() } + let ledger = try StateStore(scope: .project, environment: fixture.environment).loadLedger() + let deploy = try #require(ledger.deployments.first) + #expect(ledger.deployments.count == 1) + #expect(deploy.recipients == [.codex]) + let skill = fixture.project.appendingPathComponent(".agents/skills/review/SKILL.md") + let installed = try Data(contentsOf: skill) + #expect(String(decoding: installed, as: UTF8.self).contains("Portable review")) + try FileManager.default.removeItem(at: skill.deletingLastPathComponent()) + _ = try UpdateOperations.restore(environment: fixture.environment, offline: true) + #expect(try Data(contentsOf: skill) == installed) + } +} diff --git a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift index 6c1c36b..7872e73 100644 --- a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift +++ b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift @@ -373,3 +373,44 @@ extension PrivateNativeCompositionTests { #expect(try Data(contentsOf: manifest) == changed) } } + +extension PrivateNativeCompositionTests { + @Test func hostToggleLeavesCodexPrivateMCPReceiptAndSettingsIntact() async throws { + let fixture = try HostPluginFixture() + let config = fixture.home.appendingPathComponent(".codex/config.toml") + try fixture.write(#"[plugins."github@curated"]"# + "\nenabled = true\n", at: config) + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: config.path) + try fixture.codexBundle("curated/github/1") + try fixture.declare( + """ + components: + - kind: mcpServer + name: service + agents: [codex] + transport: + kind: stdio + executable: fixture-mcp + environment: {TOKEN: {secret: token}} + - {kind: hostPlugin, name: github, pluginId: github@curated, enabled: false, agents: [codex]} + """, scope: .user) + let provider = NativeBindings() + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: fixture.environment, bindingProvider: provider + ) { try $0.apply() } + let before = try Data(contentsOf: config) + #expect(String(decoding: before, as: UTF8.self).contains(provider.secret)) + let preview = try HostPluginExecutor.preview(scope: .user, environment: fixture.environment) + #expect(preview.first?.status.drift == .unsupported) + #expect(preview.first?.configurationChanges.isEmpty == true) + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(result.first?.outcome == .unsupported) + #expect(result.first?.diagnostic?.contains("private MCP materialization") == true) + #expect(await runner.calls.isEmpty) + #expect(try Data(contentsOf: config) == before) + let inspection = try UpdateOperations.inspect(scope: .user, environment: fixture.environment) + #expect(inspection.deployments.first?.privateMaterialization == true) + #expect(inspection.deployments.first?.status == .current) + } +} diff --git a/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift b/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift index a38ccfd..88cde22 100644 --- a/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift +++ b/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift @@ -96,9 +96,11 @@ struct SkillGovernanceTests { #expect(report.checks.compactMap(\.collision).isEmpty) #expect(report.checks.map(\.id) == ["skill-listing-budget"]) let budget = try #require(report.skillBudgets?.first) - #expect(budget.skills == 2) + #expect(budget.skills == 3) #expect(budget.advisoryThreshold == 12) - #expect(budget.utf8Bytes == ("both" + "Root" + "vendor" + "Vendé").utf8.count) + #expect( + budget.utf8Bytes + == ("both" + "Root" + "generated:both" + "Child" + "vendor:vendor" + "Vendé").utf8.count) #expect(budget.estimate.contains("Estimated")) } @@ -128,3 +130,82 @@ struct SkillGovernanceTests { !String(decoding: try JSONEncoder().encode(report), as: UTF8.self).contains("skillBudgets")) } } + +extension SkillGovernanceTests { + @Test func claudeUsesManifestNamespaceAndHonorsDisabledDefault() throws { + let fixture = try HostPluginFixture() + let claude = fixture.home.appendingPathComponent(".claude") + let bundle = claude.appendingPathComponent("plugins/cache/work/marketplace-id/1") + try fixture.write( + #"{"name":"tools","defaultEnabled":false}"#, + at: bundle.appendingPathComponent(".claude-plugin/plugin.json")) + try fixture.skill( + path: bundle.appendingPathComponent("skills/review"), name: "review", + description: "Plugin review") + try fixture.write( + #"{"plugins":{"marketplace-id@work":[{"scope":"user","installPath":"\#(bundle.path)"}]}}"#, + at: claude.appendingPathComponent("plugins/installed_plugins.json")) + let standalone = fixture.project.appendingPathComponent(".claude/skills") + try fixture.skill( + path: standalone.appendingPathComponent("review"), name: "review", description: "Standalone") + let agents: [AgentID] = [.claudeCode] + let disabled = try HostPluginExecutor.inspect(agents: agents, environment: fixture.environment) + #expect(disabled.first?.name == "tools") + #expect(disabled.first?.effectiveEnabled == false) + let before = try SkillGovernance.inspect(agents: agents, environment: fixture.environment) + #expect(before.skillBudgets?.first?.skills == 1) + + try fixture.write( + #"{"enabledPlugins":{"marketplace-id@work":true}}"#, + at: claude.appendingPathComponent("settings.json")) + let enabled = try SkillGovernance.inspect(agents: agents, environment: fixture.environment) + #expect(enabled.checks.compactMap(\.collision).isEmpty) + #expect(enabled.skillBudgets?.first?.skills == 2) + #expect( + enabled.skillBudgets?.first?.utf8Bytes + == ("review" + "Standalone" + "tools:review" + "Plugin review").utf8.count) + + try fixture.skill( + path: standalone.appendingPathComponent("exact"), name: "tools:review", description: "Exact") + let exact = try SkillGovernance.inspect(agents: agents, environment: fixture.environment) + #expect(exact.checks.compactMap(\.collision).contains(.divergentTarget)) + #expect(exact.skillBudgets?.first?.skills == 2) + } + + @Test func antigravityIncludesPersonalInventoryAndRecursivelyInheritedExcludes() throws { + let fixture = try HostPluginFixture() + let personal = fixture.home.appendingPathComponent(".gemini/config") + try fixture.write( + #"{"entries":[{"path":"external/review"}]}"#, + at: personal.appendingPathComponent("plugins.json")) + let bundle = personal.appendingPathComponent("external/review") + try fixture.write(#"{"name":"personal"}"#, at: bundle.appendingPathComponent("plugin.json")) + try fixture.skill( + path: bundle.appendingPathComponent("skills/review"), name: "review", + description: "Personal") + let agents: [AgentID] = [.antigravity] + let user = try HostPluginExecutor.inspect( + scope: .user, agents: agents, environment: fixture.environment) + #expect(user.first?.installed == true) + #expect(user.first?.effectiveEnabled == true) + #expect(user.first?.locations.map(\.path) == [bundle.path]) + + try fixture.write( + #"{"inherits":[{"path":"parent.json"}]}"#, + at: fixture.project.appendingPathComponent(".agents/plugins.json")) + try fixture.write( + #"{"inherits":[{"path":"ancestor.json"}]}"#, + at: fixture.project.appendingPathComponent("parent.json")) + try fixture.write( + #"{"exclude":["review"]}"#, at: fixture.project.appendingPathComponent("ancestor.json")) + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: review, pluginId: review, agents: [antigravity]} + """) + let project = try SkillGovernance.inspect(agents: agents, environment: fixture.environment) + #expect(project.hostPlugins.first?.effectiveEnabled == false) + #expect(project.hostPlugins.first?.drift == .unsupported) + #expect(project.skillBudgets == nil) + } +} diff --git a/Tests/ComponentsTests/SourceCatalogTests.swift b/Tests/ComponentsTests/SourceCatalogTests.swift index 4ad32b0..01b3dca 100644 --- a/Tests/ComponentsTests/SourceCatalogTests.swift +++ b/Tests/ComponentsTests/SourceCatalogTests.swift @@ -285,6 +285,49 @@ extension SourceCatalogTests { #expect(proposal.packageMetadata?.keywords == ["review"]) } + @Test func oversizedRootManifestFailsRecognitionEvenInADualManifestBundle() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"same"}"#, to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + #"{"$schema":"\#(AgentPluginManifest.schema)","name":"same"}"#, + to: "bundle/plugin.json", base: fixture.project) + let root = fixture.project.appendingPathComponent("bundle/plugin.json") + let handle = try FileHandle(forWritingTo: root) + try handle.truncate(atOffset: UInt64(SourceImportLimits().documentBytes + 1)) + try handle.close() + + do { + _ = try fixture.link( + """ + version: 1 + components: [{kind: plugin, name: test, path: bundle, source: ".", agents: [claude-code]}] + """) + Issue.record( + "An oversized manifest must fail admission even when a valid Claude manifest exists.") + } catch { + #expect(String(describing: error).lowercased().contains("limit")) + } + } + + @Test(.enabled(if: geteuid() != 0, "Permission checks require an unprivileged user")) + func unreadableRootManifestRetainsThePermissionDiagnostic() throws { + let fixture = try LinkFixture() + try fixture.write("{}", to: "bundle/plugin.json", base: fixture.project) + let root = fixture.project.appendingPathComponent("bundle/plugin.json") + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: root.path) + defer { + try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: root.path) + } + let snapshot = try ImportInput.snapshot(fixture.project) + #expect { + try PluginManifestSelection.entries(in: snapshot, container: "bundle") + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.hasPrefix("permission denied:") && reason.contains(root.path) + } + } + @Test func arbitraryRootPluginJSONDoesNotProduceAPluginChoice() throws { let fixture = try LinkFixture() try fixture.write( diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 063898f..f8b7723 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -264,6 +264,12 @@ if arguments[2].hasPrefix("acquisition-") { } else if arguments[2] == "watch-recover" { do { try store.withLock(checkpoint: { try stop($0) }, {}) } catch CoreError.transactionRecovered { } +} else if arguments[2] == "host-toggle-publication" { + try HostPluginConfigurationRoute.codex.edit( + store: store, maximumFileBytes: 4096, checkpoint: { try stop($0) }, + transform: { before in + (before ?? Data()) + Data("[plugins.'demo@test']\nenabled = false\n".utf8) + }) } else if arguments[2] == "legacy-codex-publication" { var environment = store.environment environment.environment["CODEX_HOME"] = root.appendingPathComponent("codex-override").path From 0e01d4a85417b1890e51a5c5461f27ce46f7cbad Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:24:32 +0800 Subject: [PATCH 03/10] fix: scale host plugin document node budget with maximum file size --- .../HostPlugins/HostPluginDocuments.swift | 2 +- .../HostPluginExecutorTests.swift | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginDocuments.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginDocuments.swift index 9e013bc..a27a3a4 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginDocuments.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginDocuments.swift @@ -15,7 +15,7 @@ enum HostPluginDocuments { bytes: bytes, format: format, budget: .init( limits: .init( - storage: maximumBytes * 16, work: maximumBytes * 32, nodes: 200_000, depth: 64, + storage: maximumBytes * 16, work: maximumBytes * 32, nodes: maximumBytes * 6, depth: 64, uninterruptedBytes: maximumBytes))) } diff --git a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift index add6fce..85b4549 100644 --- a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift +++ b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift @@ -478,6 +478,30 @@ extension HostPluginExecutorTests { #expect(await runner.calls.isEmpty) } + @Test func codexReadsLargeUserConfigBeyondFiftyKilobytes() throws { + let fixture = try HostPluginFixture() + var config = "" + for index in 0..<900 { + config += + "[projects.\"/tmp/project-\(String(format: "%04d", index))/with/a/long/workspace/path\"]\n" + + "trust_level = \"trusted\"\n\n" + } + config += "[plugins.\"github@curated\"]\nenabled = true\n" + #expect(config.utf8.count > 60_000) + try fixture.write(config, at: fixture.home.appendingPathComponent(".codex/config.toml")) + try fixture.write( + #"{"name":"github"}"#, + at: fixture.home.appendingPathComponent( + ".codex/plugins/cache/curated/github/1.0.0/.codex-plugin/plugin.json")) + let plugins = try HostPluginExecutor.inspect( + scope: .user, agents: [.codex], environment: fixture.environment) + #expect(plugins.count == 1) + #expect(plugins.first?.pluginId == "github@curated") + #expect(plugins.first?.installed == true) + #expect(plugins.first?.effectiveEnabled == true) + #expect(plugins.first?.drift == .current) + } + @Test func resolvesActiveLocalExportedHostPlugins() throws { let fixture = try HostPluginFixture() try fixture.declare( From 2d0f4b905c873752af79e4aeb8abc5485752421e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:56:28 +0800 Subject: [PATCH 04/10] fix: close remaining filtered-update, receipt-race, provenance and bounded-discovery gaps --- Documentation/Architecture/Package.md | 17 +++-- .../AgentsCore/HostPluginConfiguration.swift | 27 +++++++ Sources/AgentsSkills/Discovery.swift | 14 +++- .../HostPlugins/HostPluginExecutor.swift | 36 ++++++++- .../HostPlugins/HostPluginInventory.swift | 76 +++++++++++++++++-- .../HostPlugins/HostPluginTarget.swift | 68 ++++++++++++++--- Sources/AgentsUpdates/UpdatePlan.swift | 13 +++- .../Components/DeploymentConstruction.swift | 44 ++++++++++- .../CodexUserIsolationTests.swift | 12 ++- .../HostPluginExecutorTests.swift | 32 ++++++++ .../PortableBundleTests.swift | 35 +++++++++ .../PrivateNativeCompositionTests.swift | 58 ++++++++++++++ .../SkillGovernanceTests.swift | 45 +++++++++++ .../SourceCatalogInspectionTests.swift | 23 ++++++ 14 files changed, 460 insertions(+), 40 deletions(-) diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 703d5c0..745eeed 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -465,16 +465,19 @@ command, including failures, timeouts, and cancellation of an in-flight command. Cancellation preserves completed results. Codex and Antigravity project settings changes use recoverable native file publication. Codex uses the existing config coordination routes and defers to any private MCP -materialization receipt on the same file. Project settings edits require a -physical destination within project authority. Claude Code uses host commands -with its selected user, project, or local scope. +materialization receipt on the same file. Codex commands check for receipts +before launch and reconcile any receipt published during the command before +reporting success. Project settings edits require a physical destination +within project authority. Claude Code uses host commands with its selected +user, project, or local scope. The manifest's `hostPlugin` declaration takes explicit recipients and either a marketplace ID or one source-backed bundle. Source-backed inspection reads a -local checkout, including active exported groups from local producers, and -verifies the host marketplace origin or registered project bundle path before -reconciling an existing registration. Conflicting enablement declarations for -one host, scope and plugin ID are surfaced before execution. +local checkout, including active exported groups from local producers. Stored +bundle exports come from a verified snapshot. Existing registrations are +reconciled against the host marketplace origin or registered project bundle +path. Conflicting enablement declarations for one host, scope and plugin ID +are surfaced before execution. The combined update graph continues to freeze and replay `kind: plugin` through its existing resource and transaction path. diff --git a/Sources/AgentsCore/HostPluginConfiguration.swift b/Sources/AgentsCore/HostPluginConfiguration.swift index 67a25cd..fe20856 100644 --- a/Sources/AgentsCore/HostPluginConfiguration.swift +++ b/Sources/AgentsCore/HostPluginConfiguration.swift @@ -56,6 +56,33 @@ package enum HostPluginConfigurationRoute { } } + /// Vendor commands run unlocked. Readback must check for a managed generation published + /// while the command was running, even when the plugin itself now looks current. + package func checkAfterHostCommand(store: StateStore) throws { + let native = route(store.scope) + try store.withReadLock(footprint: [native]) { + try requireScope(store) + let target = try store.nativeTarget(for: native) + try requireProjectAuthority(target.url, store: store) + guard try store.hasMaterializationReceipt(for: target) else { return } + let settings = "\(store.scope.rawValue)-scope Codex settings" + do { + let live = try TargetPrecondition(target.url) + guard live.exists, try store.materializationReceipt(for: target) != nil else { + throw CoreError.invalidState("private settings or their receipt are missing") + } + try live.validate() + } catch { + throw CoreError.invalidState( + "A private MCP materialization receipt for \(settings) no longer matches the live file. Reconcile the managed MCP settings and receipt before retrying host plugin sync." + ) + } + throw CoreError.invalidState( + "A private MCP materialization appeared in \(settings) during the host command. Review the managed MCP settings and plugin state before retrying host plugin sync." + ) + } + } + package func edit( store: StateStore, maximumFileBytes: Int, checkpoint: @escaping (String) throws -> Void = { _ in }, diff --git a/Sources/AgentsSkills/Discovery.swift b/Sources/AgentsSkills/Discovery.swift index 1c4f2ec..803bd1c 100644 --- a/Sources/AgentsSkills/Discovery.swift +++ b/Sources/AgentsSkills/Discovery.swift @@ -307,6 +307,14 @@ enum Discovery { var directories: [URL] = [] var groups: [String: String] = [:] let decoder = JSONDecoder() + let maximumManifestBytes = 16 * 1024 * 1024 + + func metadataBytes(_ path: String) throws -> Data? { + let file = base.appendingPathComponent(path).resolvingSymlinksInPath() + guard !isDirectory(file) else { return nil } + let input = try TargetPrecondition.readingFile(file, maximumFileBytes: maximumManifestBytes) + return input.bytes + } func add(_ root: URL, name: String?, skills: [String], prefer: Bool = false) { for path in skills where path.hasPrefix("./") { @@ -319,8 +327,7 @@ enum Discovery { } for path in [".claude-plugin/marketplace.json", ".agents/plugins/marketplace.json"] { - let file = base.appendingPathComponent(path) - guard let data = try FileSystem.readUnlessDenied(at: file), + guard let data = try metadataBytes(path), let manifest = try? decoder.decode(MarketplaceManifest.self, from: data) else { continue } let root = manifest.metadata?.pluginRoot @@ -339,8 +346,7 @@ enum Discovery { } for path in [".claude-plugin/plugin.json", "plugin.json"] { - let file = base.appendingPathComponent(path) - guard let data = try FileSystem.readUnlessDenied(at: file), + guard let data = try metadataBytes(path), let manifest = try? decoder.decode(PluginManifest.self, from: data), path != "plugin.json" || manifest.schema == AgentPluginManifest.schema else { continue } diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift index 578e839..71a0ff9 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift @@ -336,13 +336,45 @@ public enum HostPluginExecutor { guard !ran.contains(command.argv) else { return finish(.failed, "Host readback did not confirm the completed command.") } + let codexStores = + target.agent == .codex + ? (target.scope == .user ? [InstallScope.user] : [.user, .project]).map { + StateStore(scope: $0, environment: locations.environment) + } : [] + do { + for store in codexStores { + try HostPluginConfigurationRoute.codex.checkEditable(store: store) + } + } catch CoreError.unsupported(let reason) { + return finish(.unsupported, reason) + } catch { + return finish(.failed, "Codex settings could not be verified before the host command.") + } ran.append(command.argv) let result = await runner.run(argv: command.argv, environment: locations.environment) + let readback: @Sendable () -> (Plan, String?) = { + let observed = plan(target, locations: locations) + do { + for store in codexStores { + try HostPluginConfigurationRoute.codex.checkAfterHostCommand(store: store) + } + } catch CoreError.invalidState(let reason) { + return (observed, reason) + } catch { + return ( + observed, + "Codex settings could not be verified after the host command. Check the managed MCP settings before retrying host plugin sync." + ) + } + return (observed, nil) + } + let reconciled = + Task.isCancelled ? await Task.detached(operation: readback).value : readback() + current = reconciled.0 + if let conflict = reconciled.1 { return finish(.failed, conflict) } if Task.isCancelled { - current = await Task.detached { plan(target, locations: locations) }.value return finish(.failed, "Host plugin synchronization was cancelled.") } - current = plan(target, locations: locations) switch result { case .success: if command.role == .install, current.preview.status.installed == true { installed = true } diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift index 4068dfc..7fad91b 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginInventory.swift @@ -139,6 +139,8 @@ struct HostPluginLocations: Sendable { return false } + private static let claudeMarketplaceManifest = ".claude-plugin/marketplace.json" + private func claude( _ selection: ClaudePluginScope, scope: InstallScope, verifyMarketplace: Bool ) throws -> HostPluginInventory { @@ -165,9 +167,21 @@ struct HostPluginLocations: Sendable { } let market = try HostPluginDocuments.read( claudeUser.appendingPathComponent("plugins/known_marketplaces.json")) - for (name, value) in try HostPluginDocuments.fields(market?.hostValue([])) { + let registrations = try HostPluginDocuments.fields(market?.hostValue([])) + for (name, value) in registrations { try result.marketplaces[name, default: []].append(claudeMarketplaceOrigin(value)) } + var catalogEntries: [String: [String: NativeValue]] = [:] + func marketplaceDefault(for id: String) throws -> Bool? { + let parts = id.split(separator: "@", omittingEmptySubsequences: false) + guard parts.count == 2, HostPluginDocuments.safeID(String(parts[1])) else { return nil } + let name = String(parts[1]) + if catalogEntries[name] == nil { + catalogEntries[name] = try claudeCatalogEntries( + name: name, registration: registrations[name]) + } + return try HostPluginDocuments.boolean(catalogEntries[name]?[String(parts[0])]) + } let ids = settings.values.reduce(into: Set(entries.keys)) { $0.formUnion($1.keys) } for id in ids.sorted() { let installations = try HostPluginDocuments.list(entries[id]).map { @@ -202,10 +216,13 @@ struct HostPluginLocations: Sendable { let name = try manifest?.hostValue(["name"])?.hostString ?? String(id.split(separator: "@").first ?? Substring(id)) - let defaultEnabled = try HostPluginDocuments.boolean(manifest?.hostValue(["defaultEnabled"])) + let effective: Bool? = + try locations.isEmpty + ? nil + : configured ?? marketplaceDefault(for: id) + ?? HostPluginDocuments.boolean(manifest?.hostValue(["defaultEnabled"])) ?? true result.plugins[id] = .init( - id: id, name: name, installed: installed, explicit: explicit, - effective: locations.isEmpty ? nil : (configured ?? defaultEnabled ?? true), + id: id, name: name, installed: installed, explicit: explicit, effective: effective, locations: locations) } return result @@ -224,14 +241,59 @@ struct HostPluginLocations: Sendable { file.deletingLastPathComponent().lastPathComponent == ".claude-plugin" else { return nil } return file.deletingLastPathComponent().deletingLastPathComponent().path - case "git", "url": + case "git", "github": + // The declaration's repository selector denotes the default catalog. + if let path = source["path"] { + guard let path = path.hostString, !path.contains("\\"), + (try? PathSafety.sanitizeSubpath(path)) == Self.claudeMarketplaceManifest + else { return nil } + } + let locator = source["source"]?.hostString == "github" ? "repo" : "url" + return source["ref"] == nil ? source[locator]?.hostString : nil + case "url": return source["ref"] == nil ? source["url"]?.hostString : nil - case "github": - return source["ref"] == nil ? source["repo"]?.hostString : nil default: return nil } } + private func claudeCatalogEntries(name: String, registration: NativeValue?) + throws -> [String: NativeValue] + { + let fields = try HostPluginDocuments.fields(registration) + let source = try HostPluginDocuments.fields(fields["source"]) + let type = source["source"]?.hostString + let file: URL + if type == "file", let path = source["path"]?.hostString, path.hasPrefix("/") { + file = URL(fileURLWithPath: path) + } else { + let installed = fields["installLocation"]?.hostString + let location = installed ?? (type == "directory" ? source["path"]?.hostString : nil) + if let location, !location.hasPrefix("/") { return [:] } + let root = + location.map { URL(fileURLWithPath: $0) } + ?? claudeUser.appendingPathComponent("plugins/marketplaces").appendingPathComponent(name) + if type == "url", !Self.isDirectory(root), installed != nil { + file = root + } else { + let path = + (type == "git" || type == "github") ? source["path"]?.hostString : nil + file = try PathSafety.resolvedChild( + base: root, subpath: path ?? Self.claudeMarketplaceManifest) + } + } + guard let catalog = try HostPluginDocuments.read(file), + try catalog.hostValue(["name"])?.hostString == name + else { return [:] } + var defaults: [String: NativeValue] = [:] + for entry in try HostPluginDocuments.list(catalog.hostValue(["plugins"])) { + let plugin = try HostPluginDocuments.fields(entry) + if let id = plugin["name"]?.hostString, let value = plugin["defaultEnabled"] { + defaults[id] = value + } + } + return defaults + } + private func antigravity(_ scope: InstallScope) throws -> HostPluginInventory { let config = try HostPluginDocuments.read(antigravityUser.appendingPathComponent("config.json")) let settings = try HostPluginDocuments.fields(config?.hostValue(["plugins"])) diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift index 964afc4..ffcd8d3 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift @@ -43,7 +43,7 @@ struct HostPluginTarget: Sendable { } var targets: [Self] = [] var seenGroups = Set<[String]>() - var producers: [String: Context] = [:] + var producers: [[String]: Context] = [:] func permits(_ condition: DeclarationCondition?, agent: AgentID) -> Bool { (condition?.agents?.contains(agent) ?? true) && (condition?.scopes?.contains(scope) ?? true) @@ -66,27 +66,51 @@ struct HostPluginTarget: Sendable { guard let source = context.declaration.sources[alias], source.kind == .local, source.requirement == nil else { throw CoreError.unsupported("Host plugin exports require a readable local source.") } - let origin = source.localURL(environment: environment).resolvingSymlinksInPath() + let declared = source.localURL(environment: environment) + let origin = declared.resolvingSymlinksInPath() let root = try PathSafety.resolvedChild(base: origin, subpath: source.path ?? ".") .resolvingSymlinksInPath() - let file = root.appendingPathComponent( - root.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml") + let manifest = root.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml" + let file = root.appendingPathComponent(manifest) guard PathSafety.isContained(file.resolvingSymlinksInPath(), in: origin) else { throw CoreError.unsafePath("Host plugin export escapes its source.") } - if let cached = producers[root.path] { return cached } - guard producers.count < 256, - let data = try TargetPrecondition.readingFile( + let stored = storedProducer(declared: declared, physical: origin, store: store) + let producerKey = [root.path, stored?.source.path ?? ""] + if let cached = producers[producerKey] { return cached } + guard producers.count < 256 else { + throw CoreError.unsupported("Host plugin export declaration is unavailable.") + } + let bytes: Data? + if let stored { + // Read the exact snapshot whose marker and tree passed stored-source admission. + bytes = try stored.store.withReadLock { + try SourceResolutionSession.withTemporaryRead(store: stored.store) { session in + let snapshot = try session.localSnapshot( + .init(kind: .local, location: stored.source.path, path: source.path)) + let relative = try snapshot.relativePath( + snapshot.directory().appendingPathComponent(manifest)) + return try TargetPrecondition.readingFile( + snapshot.resource(relative), maximumFileBytes: ManifestLimits.Input.bytes + ).bytes + } + } + } else { + bytes = try TargetPrecondition.readingFile( file, maximumFileBytes: ManifestLimits.Input.bytes - ).bytes - else { throw CoreError.unsupported("Host plugin export declaration is unavailable.") } + ) + .bytes + } + guard let data = bytes else { + throw CoreError.unsupported("Host plugin export declaration is unavailable.") + } let document = try DeclarationDocument(bytes: Array(data), identity: .init(file.path)) var producerEnvironment = environment producerEnvironment.projectDirectory = root let loaded = try ManifestProjection.declaration( of: document, environment: producerEnvironment) let result = Context(root: root, declaration: loaded) - producers[root.path] = result + producers[producerKey] = result return result } func visit( @@ -120,7 +144,7 @@ struct HostPluginTarget: Sendable { marketplaceSource: nil, issue: ( .unsupported, - "Host plugins could not be inspected in group '\(label)'. Use a readable local exported group." + "Host plugins could not be inspected in group '\(label)'. Use a readable local exported group or verify the installed bundle." ))) } return @@ -159,6 +183,28 @@ struct HostPluginTarget: Sendable { return targets } + private static func storedProducer(declared: URL, physical: URL, store: StateStore) + -> (store: StateStore, source: URL)? + { + let other = StateStore( + scope: store.scope == .user ? .project : .user, environment: store.environment) + for candidate in [store, other] { + if BundleSourceLocation.container(of: declared, in: candidate) != nil { + return (candidate, declared) + } + let key = physical.deletingLastPathComponent().lastPathComponent + guard physical.lastPathComponent == BundleSourceLocation.tree, + BundleSourceLocation.isKey(key) + else { continue } + let canonical = candidate.directory.appendingPathComponent(BundleSourceLocation.directory) + .appendingPathComponent(key).appendingPathComponent(BundleSourceLocation.tree) + if canonical.resolvingSymlinksInPath().path == physical.path { + return (candidate, canonical) + } + } + return nil + } + private static func resolve( _ declaration: HostPluginDeclaration, agent: AgentID, scope: InstallScope, root: URL, sources: [String: SourceDeclaration], environment: RuntimeEnvironment diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 8466d70..7f6dc59 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -466,9 +466,18 @@ final class UpdatePlan { let complete = try DeploymentConstruction.complete( native, linked: linked, store: store, previous: previous, platform: platform, roots: roots, session: session) + var desired = complete.ledger + let names = Set(request.names) + try DeploymentConstruction.preserveUnselectedLegacyCodexSkills( + in: &desired, previous: previous, scope: store.scope, roots: roots + ) { owner, ledger in + try ArtifactAggregation.selects( + owner, in: ledger, roots: roots, kinds: request.kinds, names: names, + identities: request.selectedIdentities, retargetedInstructions: retargetedInstructions) + } if marketplaceLock == nil { let required = try SkillLifecycle.installationTargets(previous, store: store).merging( - SkillLifecycle.installationTargets(complete.ledger, store: store), + SkillLifecycle.installationTargets(desired, store: store), uniquingKeysWith: { _, next in next }) guard Set(required.keys).isSubset(of: Set(installations.keys)) else { throw RequiredRoutes(routes: routes, installations: required) @@ -483,7 +492,7 @@ final class UpdatePlan { try checkpoint("plan.skills") let roots = store.ledgerRoots(recordedIn: previous) return try LedgerReplay.withPreparedLowerings( - complete.ledger, store: store, roots: roots, limits: .standard, + desired, store: store, roots: roots, limits: .standard, sourcePolicy: sourcePolicy.effective, requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin, acquisitions: session.acquisitions diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift index 17c5c57..d330837 100644 --- a/Sources/Components/DeploymentConstruction.swift +++ b/Sources/Components/DeploymentConstruction.swift @@ -11,10 +11,7 @@ package enum DeploymentConstruction { var next = previous for index in next.deployments.indices { let deployment = next.deployments[index] - if deployment.route == "agents/skill@1", deployment.target.kind == .registered, - deployment.target.root == "skills-codex", deployment.recipients == [.codex], - try selecting(deployment) - { + if isCodexSkill(deployment, root: "skills-codex"), try selecting(deployment) { next.deployments[index].target.root = AgentRegistry.skillRootKey(for: .codex, scope: scope) next.deployments[index].target.path = PathSafety.sanitizeName(deployment.target.path) } @@ -22,6 +19,45 @@ package enum DeploymentConstruction { return next } + private static func isCodexSkill(_ deployment: LedgerDeployment, root: String) -> Bool { + deployment.route == "agents/skill@1" && deployment.target.kind == .registered + && deployment.target.root == root && deployment.recipients == [.codex] + } + + package static func preserveUnselectedLegacyCodexSkills( + in next: inout ResolvedLedger, previous: ResolvedLedger, scope: InstallScope, + roots: [String: URL], selecting: (String, ResolvedLedger) throws -> Bool + ) throws { + guard scope == .user else { return } + var historical: [String: Set] = [:] + for deployment in previous.deployments where isCodexSkill(deployment, root: "skills-codex") { + guard try !deployment.owners.contains(where: { try selecting($0, previous) }) else { + continue + } + for owner in deployment.owners { + let key = try LedgerImpact.identity( + previous.components[owner]!, ledger: previous, roots: roots) + historical[key, default: []].insert(deployment.target) + } + } + guard !historical.isEmpty else { return } + let root = AgentRegistry.skillRootKey(for: .codex, scope: scope) + for index in next.deployments.indices { + let deployment = next.deployments[index] + guard isCodexSkill(deployment, root: root), + try !deployment.owners.contains(where: { try selecting($0, next) }) + else { continue } + let targets = try deployment.owners.reduce(into: Set()) { targets, owner in + let key = try LedgerImpact.identity(next.components[owner]!, ledger: next, roots: roots) + targets.formUnion(historical[key] ?? []) + } + guard targets.count <= 1 else { + throw CoreError.invalidState("ambiguous historical target for an unselected Codex skill") + } + if let target = targets.first { next.deployments[index].target = target } + } + } + package static func validateCopiedSkill(_ tree: URL) throws { guard let real = PathSafety.realPath(tree.path), let children = FileManager.default.enumerator( diff --git a/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift b/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift index 66b27bc..afbbf91 100644 --- a/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift +++ b/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift @@ -63,7 +63,8 @@ struct CodexUserIsolationTests { } } - @Test func instructionOnlyRestorePreservesLegacySkillOwnership() throws { + @Test(arguments: [false, true]) + func instructionOnlyRestoreOrUpdatePreservesLegacySkillOwnership(_ restore: Bool) throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "managed") let instructions = fixture.repo.appendingPathComponent("instructions") @@ -83,8 +84,13 @@ struct CodexUserIsolationTests { try FileManager.default.createDirectory(at: privateSkill, withIntermediateDirectories: true) try Data("unmanaged private".utf8).write(to: privateSkill.appendingPathComponent("SKILL.md")) - _ = try InstructionOperations.installResolvedReport( - scope: .user, environment: fixture.environment) + if restore { + _ = try InstructionOperations.installResolvedReport( + scope: .user, environment: fixture.environment) + } else { + _ = try InstructionOperations.updateInstalled( + scope: .user, environment: fixture.environment, apply: true) + } let ledger = try fixture.store(.user).loadLedger() #expect( ledger.deployments.first { $0.route == "agents/skill@1" }?.target.root == "skills-codex") diff --git a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift index 85b4549..e649dce 100644 --- a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift +++ b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift @@ -400,6 +400,38 @@ extension HostPluginExecutorTests { #expect(await registrationRunner.calls == [add]) } + @Test(arguments: ["github", "git"]) + func claudeRejectsCustomCatalogPathForADefaultRepositorySelector(_ type: String) async throws { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: review, pluginId: review@work, marketplace: https://github.com/team/work.git, agents: [claude-code]} + """, scope: .user) + let registry = fixture.home.appendingPathComponent(".claude/plugins/known_marketplaces.json") + let repository = + type == "github" ? #""repo":"team/work""# : #""url":"https://github.com/team/work.git""# + func record(_ path: String) -> String { + """ + {"work":{"source":{"source":"\(type)",\(repository),"path":"\(path)"}}} + """ + } + try fixture.write(record("catalogs/foreign.json"), at: registry) + let runner = RecordingHostRunner { _, _ in .failed } + let rejected = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(rejected.first?.outcome == .unsupported) + #expect(rejected.first?.diagnostic?.contains("provenance") == true) + #expect(await runner.calls.isEmpty) + + try fixture.write(record("./.claude-plugin/marketplace.json"), at: registry) + let preview = try HostPluginExecutor.preview(scope: .user, environment: fixture.environment) + #expect( + preview.first?.commands.first == [ + "claude", "plugin", "install", "review@work", "--scope", "user", + ]) + } + @Test func claudeDetectsForeignMarketplaceDeclaredInProjectSettings() async throws { let fixture = try HostPluginFixture() try fixture.declare( diff --git a/Tests/AgentsUpdatesTests/PortableBundleTests.swift b/Tests/AgentsUpdatesTests/PortableBundleTests.swift index fd60dc7..2be503c 100644 --- a/Tests/AgentsUpdatesTests/PortableBundleTests.swift +++ b/Tests/AgentsUpdatesTests/PortableBundleTests.swift @@ -58,6 +58,41 @@ struct PortableBundleTests { atPath: root.appendingPathComponent("skills/demo/SKILL.md").path)) } + @Test func hostSyncRejectsTamperedStoredBundleExport() async throws { + let bundle = try BundleOperations.inspect(BundleFixture().export()) + let member = try #require(bundle.components.first { $0.kind == .skills }) + let consumer = try UpdateFixture() + let preview = try BundleOperations.previewImport( + bundle, selections: [.init(componentID: member.id, targets: [.codex])], + scope: .project, environment: consumer.environment) + _ = try BundleOperations.withPreparedImport(preview) { try $0.apply() } + let declaration = try consumer.store.loadDeclaration() + let use = try #require(declaration.uses.first) + let alias = try #require(use.source) + let source = try #require(declaration.sources[alias]) + let tree = source.localURL(environment: consumer.environment) + #expect(BundleSourceLocation.container(of: tree, in: consumer.store) != nil) + #expect( + try HostPluginExecutor.preview(agents: [.codex], environment: consumer.environment).isEmpty) + try consumer.write( + """ + version: 1 + exports: [\(use.name)] + groups: + \(use.name): + components: + - {kind: hostPlugin, name: injected, pluginId: injected@foreign, agents: [codex]} + """, to: tree.appendingPathComponent(".agent/agents.yaml")) + + let runner = RecordingHostRunner { _, _ in .failed } + let result = try await HostPluginExecutor.sync( + agents: [.codex], apply: true, environment: consumer.environment, runner: runner) + #expect(result.map(\.outcome) == [.unsupported]) + #expect(result.first?.status.name == alias + ":" + use.name) + #expect(result.first?.status.pluginId == nil) + #expect(await runner.calls.isEmpty) + } + @Test(arguments: [InstallScope.project, .user]) func lockedComponentsRoundTripAcrossIndependentHomes(_ scope: InstallScope) throws { let publisher = try BundleFixture() diff --git a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift index 7872e73..d0be0cc 100644 --- a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift +++ b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift @@ -413,4 +413,62 @@ extension PrivateNativeCompositionTests { #expect(inspection.deployments.first?.privateMaterialization == true) #expect(inspection.deployments.first?.status == .current) } + + @Test(arguments: [false, true]) + func codexInstallDetectsPrivateReceiptPublishedDuringCommand(_ stale: Bool) async throws { + let fixture = try HostPluginFixture() + let config = fixture.home.appendingPathComponent(".codex/config.toml") + try fixture.declare( + """ + components: + - kind: mcpServer + name: service + agents: [codex] + transport: + kind: stdio + executable: fixture-mcp + environment: {TOKEN: {secret: token}} + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} + """, scope: .user) + let provider = NativeBindings() + let toggle = #"[plugins."github@curated"]"# + "\nenabled = true\n" + let runner = RecordingHostRunner { argv, environment in + guard argv == ["codex", "plugin", "add", "github@curated", "--json"] else { return .failed } + do { + if !stale { + try fixture.write(toggle, at: config) + try FileManager.default.setAttributes( + [.posixPermissions: 0o600], ofItemAtPath: config.path) + } + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: environment, bindingProvider: provider + ) { try $0.apply() } + if stale { + let handle = try FileHandle(forWritingTo: config) + defer { try? handle.close() } + try handle.seekToEnd() + try handle.write(contentsOf: Data(("\n" + toggle).utf8)) + } + try fixture.codexBundle("curated/github/1") + return .success + } catch { + Issue.record(error) + return .failed + } + } + let result = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(result.first?.outcome == .failed) + #expect(result.first?.status.installed == true) + #expect(result.first?.status.effectiveEnabled == true) + #expect(await runner.calls.count == 1) + #expect(provider.calls.withLock { $0 } == 1) + let diagnostic = try #require(result.first?.diagnostic) + if stale { + #expect(diagnostic.contains("no longer matches the live file")) + } else { + #expect(diagnostic.contains("appeared") && diagnostic.contains("during the host command")) + } + #expect(diagnostic.contains("before retrying")) + } } diff --git a/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift b/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift index 88cde22..7e463d3 100644 --- a/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift +++ b/Tests/AgentsUpdatesTests/SkillGovernanceTests.swift @@ -172,6 +172,51 @@ extension SkillGovernanceTests { #expect(exact.skillBudgets?.first?.skills == 2) } + @Test(arguments: [nil, true] as [Bool?]) + func claudeMarketplaceDefaultPrecedesManifestAndPlansEnable(_ manifestDefault: Bool?) async throws + { + let fixture = try HostPluginFixture() + let claude = fixture.home.appendingPathComponent(".claude") + let bundle = claude.appendingPathComponent("plugins/cache/work/review/1") + let catalog = claude.appendingPathComponent("plugins/marketplaces/work") + let manifest = + #"{"name":"tools""# + (manifestDefault == true ? #","defaultEnabled":true"# : "") + "}" + try fixture.write(manifest, at: bundle.appendingPathComponent(".claude-plugin/plugin.json")) + try fixture.skill( + path: bundle.appendingPathComponent("skills/review"), name: "review", description: "Review") + try fixture.write( + #"{"plugins":{"review@work":[{"scope":"user","installPath":"\#(bundle.path)"}]}}"#, + at: claude.appendingPathComponent("plugins/installed_plugins.json")) + try fixture.write( + #"{"work":{"source":{"source":"github","repo":"team/work","path":"catalogs/marketplace.json"},"installLocation":"\#(catalog.path)"}}"#, + at: claude.appendingPathComponent("plugins/known_marketplaces.json")) + try fixture.write( + #"{"name":"work","plugins":[{"name":"review","defaultEnabled":false}]}"#, + at: catalog.appendingPathComponent("catalogs/marketplace.json")) + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: review, pluginId: review@work, agents: [claude-code]} + """, scope: .user) + let inventory = try HostPluginExecutor.inspect( + scope: .user, agents: [.claudeCode], environment: fixture.environment) + #expect(inventory.first?.installed == true) + #expect(inventory.first?.explicitEnabled == nil) + #expect(inventory.first?.effectiveEnabled == false) + let doctor = try SkillGovernance.inspect( + scope: .user, agents: [.claudeCode], environment: fixture.environment) + #expect(doctor.skillBudgets == nil) + let runner = RecordingHostRunner { _, _ in .failed } + let preview = try await HostPluginExecutor.sync( + scope: .user, agents: [.claudeCode], environment: fixture.environment, runner: runner) + #expect(preview.first?.status.drift == .enablement) + #expect( + preview.first?.preview.commands == [ + ["claude", "plugin", "enable", "review@work", "--scope", "user"] + ]) + #expect(await runner.calls.isEmpty) + } + @Test func antigravityIncludesPersonalInventoryAndRecursivelyInheritedExcludes() throws { let fixture = try HostPluginFixture() let personal = fixture.home.appendingPathComponent(".gemini/config") diff --git a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift index 4a08890..5f9f7ba 100644 --- a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift +++ b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift @@ -8,6 +8,29 @@ import Testing @Suite("Captured source catalog additions", .serialized) struct SourceCatalogInspectionTests { + @Test(arguments: ["plugin.json", ".agents/plugins/marketplace.json"]) + func rejectsOversizedPluginMetadataDuringSkillDiscovery(_ path: String) throws { + let fixture = try UpdateFixture() + let producer = fixture.root.appendingPathComponent("producer") + let manifest = producer.appendingPathComponent(path) + try fixture.write(#"{"name":"unrelated"}"#, to: manifest) + let invalidSkill = producer.appendingPathComponent("SKILL.md") + try Data([0xff]).write(to: invalidSkill) + func inspect() throws -> SourceCatalogInspection { + try UpdateOperations.inspectSource( + alias: "producer", source: .init(kind: .local, location: producer.path), + environment: fixture.environment) + } + #expect(throws: CoreError.invalidSource("SKILL.md must be UTF-8")) { try inspect() } + + let handle = try FileHandle(forWritingTo: manifest) + try handle.truncate(atOffset: 16 * 1024 * 1024 + 1) + try handle.close() + #expect(throws: CoreError.invalidState("file exceeds the admitted byte limit")) { + try inspect() + } + } + @Test func instructionSelectionPreparesAppliesAndRejectsForeignDestination() throws { let f = try UpdateFixture() let other = try UpdateFixture() From 117baf381143287e310372f1e248381d39b0fbb9 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:23:02 +0800 Subject: [PATCH 05/10] fix: coordinate Codex host plugin commands with private materialization receipts --- Documentation/Architecture/Package.md | 11 +- Documentation/Architecture/State.md | 9 ++ Sources/AgentsCore/CodexHostCommandLock.swift | 90 +++++++++++ Sources/AgentsCore/FileTransaction.swift | 3 + .../AgentsCore/HostPluginConfiguration.swift | 82 ++++++---- .../AgentsCore/NativeTargetCoordination.swift | 18 ++- .../AgentsCore/PrivateMaterialization.swift | 13 ++ .../HostPlugins/HostPluginExecutor.swift | 49 +++--- Sources/Components/ArtifactAggregation.swift | 50 +++--- .../PrivateNativeCompositionTests.swift | 149 ++++++++++++------ 10 files changed, 337 insertions(+), 137 deletions(-) create mode 100644 Sources/AgentsCore/CodexHostCommandLock.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 745eeed..591fb98 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -465,11 +465,12 @@ command, including failures, timeouts, and cancellation of an in-flight command. Cancellation preserves completed results. Codex and Antigravity project settings changes use recoverable native file publication. Codex uses the existing config coordination routes and defers to any private MCP -materialization receipt on the same file. Codex commands check for receipts -before launch and reconcile any receipt published during the command before -reporting success. Project settings edits require a physical destination -within project authority. Claude Code uses host commands with its selected -user, project, or local scope. +materialization receipt on the same file. A separate per-target advisory lock +excludes private Codex receipt publication while a host command runs. Codex +preflight and readback verify existing receipt evidence, including on no-op +syncs. Project settings edits require a physical destination within project +authority. Claude Code uses host commands with its selected user, project, or +local scope. The manifest's `hostPlugin` declaration takes explicit recipients and either a marketplace ID or one source-backed bundle. Source-backed inspection reads a diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index d9d4295..e6afa98 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -593,6 +593,7 @@ 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. @@ -625,6 +626,14 @@ 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. +Codex vendor commands and private receipt publishers share a separate advisory +lock at `.agents-host-commands/config.toml.lock` under the physical settings +parent. The host takes it before a brief scope read and holds it through the +command with scope and shared-resource locks released. Managed writers try the +host lock without waiting and retain it through commit or rollback. A contended +writer stops before publishing settings or a receipt and can retry after the +host command completes. + 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. diff --git a/Sources/AgentsCore/CodexHostCommandLock.swift b/Sources/AgentsCore/CodexHostCommandLock.swift new file mode 100644 index 0000000..1ba9c3a --- /dev/null +++ b/Sources/AgentsCore/CodexHostCommandLock.swift @@ -0,0 +1,90 @@ +import CPlatform +import Dispatch +import Foundation +import Synchronization + +/// The pathname is scoped by the physical settings parent. Keep the lock file in place +/// so successive commands and transactions always contend on the same inode. +final class CodexHostCommandLock: Sendable { + private static let directoryName = ".agents-host-commands" + private let descriptor: Atomic + + private init(descriptor: Int32) { self.descriptor = Atomic(descriptor) } + + deinit { release() } + + func release() { + let open = descriptor.exchange(-1, ordering: .relaxed) + if open >= 0 { close(open) } + } + + static func acquire(for target: URL, wait: Bool) throws -> CodexHostCommandLock { + let url = target.deletingLastPathComponent() + let parent: DirectoryHandle + do { + parent = try DirectoryHandle(at: url, reportMissing: true) + } catch CoreError.notFound { + do { + parent = try DirectoryHandle(at: url, create: true) + } catch { + // A concurrent first writer may have created the settings parent. + guard let existing = try? DirectoryHandle(at: url) else { throw error } + parent = existing + } + } + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: parent.descriptor, protectingOwner: geteuid()) + if mkdirat(parent.descriptor, directoryName, 0o700) != 0, errno != EEXIST { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(directoryName), + otherwise: .invalidState("cannot create the Codex host command lock directory")) + } + let directory = try parent.child(directoryName) + let directoryAccess = try FileAccessEvidence.requirePrivate(descriptor: directory.descriptor) + let name = target.lastPathComponent + ".lock" + var descriptor: Int32 + repeat { + descriptor = openat( + directory.descriptor, name, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, + S_IRUSR | S_IWUSR) + } while descriptor < 0 && errno == EINTR + guard descriptor >= 0 else { + throw FileSystem.posixError( + errno, at: directory.url.appendingPathComponent(name), + otherwise: .invalidState("cannot open the Codex host command lock")) + } + let lock = CodexHostCommandLock(descriptor: descriptor) + let access = try FileAccessEvidence.requirePrivate(descriptor: descriptor) + guard access.identity.kind == S_IFREG else { + throw CoreError.unsafePath("the Codex host command lock must be a regular file") + } + let mode = wait ? LOCK_EX : LOCK_EX | LOCK_NB + while platform_flock(descriptor, mode) != 0 { + let failure = errno + if failure == EINTR { continue } + if !wait, failure == EWOULDBLOCK || failure == EAGAIN { + throw CoreError.invalidState( + "a host plugin command is currently modifying this configuration; retry after it completes" + ) + } + throw CoreError.invalidState("cannot acquire the Codex host command lock") + } + guard try parent.info(directoryName).map(FileObjectIdentity.init) == directoryAccess.identity, + try directory.info(name).map(FileObjectIdentity.init) == access.identity + else { throw CoreError.invalidState("the Codex host command lock changed") } + try access.validate(descriptor: descriptor) + return lock + } + + /// Blocking advisory lock acquisition must not occupy a Swift cooperative executor thread. + static func acquireForHost(_ targets: [URL]) async throws -> [CodexHostCommandLock] { + try await withCheckedThrowingContinuation { continuation in + DispatchQueue.global().async { + continuation.resume( + with: Result { + try targets.map { try acquire(for: $0, wait: true) } + }) + } + } + } +} diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index fab0cf5..7d2b8ce 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -473,6 +473,9 @@ package final class FileTransaction { package func commit() throws { guard !requests.isEmpty else { return } + for request in requests where request.security.replacement == .privateMaterialization { + try store.excludeHostCommands(for: request.path, at: request.evidence.physicalURL) + } let shared = try requests.filter { try TransactionPaths(store: store).coordinationRoute(for: $0.path) != nil } diff --git a/Sources/AgentsCore/HostPluginConfiguration.swift b/Sources/AgentsCore/HostPluginConfiguration.swift index fe20856..b7af08d 100644 --- a/Sources/AgentsCore/HostPluginConfiguration.swift +++ b/Sources/AgentsCore/HostPluginConfiguration.swift @@ -33,14 +33,33 @@ package enum HostPluginConfigurationRoute { } } - private func editableTarget(_ store: StateStore) throws -> MaterializationTarget { + private func checkedTarget( + _ store: StateStore, forMutation: Bool, expected: URL? = nil + ) throws -> MaterializationTarget { try requireScope(store) let target = try store.nativeTarget(for: route(store.scope)) try requireProjectAuthority(target.url, store: store) + if let expected, !expected.path.utf8.elementsEqual(target.url.path.utf8) { + throw CoreError.invalidState( + "Codex settings location changed while acquiring the host command lock") + } if self == .codex, try store.hasMaterializationReceipt(for: target) { - throw CoreError.unsupported( - "Codex settings contain a private MCP materialization. Reconcile it before syncing host plugins." - ) + do { + let live = try TargetPrecondition(target.url) + guard live.exists, try store.materializationReceipt(for: target) != nil else { + throw CoreError.invalidState("private settings or their receipt are missing") + } + try live.validate() + } catch { + throw CoreError.unsupported( + "A private MCP materialization receipt for \(store.scope.rawValue)-scope Codex settings no longer matches the live file. Reconcile the managed MCP settings and receipt before retrying host plugin sync." + ) + } + if forMutation { + throw CoreError.unsupported( + "Codex settings contain a private MCP materialization. Reconcile it before syncing host plugins." + ) + } } return target } @@ -49,38 +68,39 @@ package enum HostPluginConfigurationRoute { try requireScope(store) } - package func checkEditable(store: StateStore) throws { - try requireScope(store) + package func checkReceipt(store: StateStore, forMutation: Bool) throws { try store.withReadLock(footprint: [route(store.scope)]) { - _ = try editableTarget(store) + _ = try checkedTarget(store, forMutation: forMutation) } } - /// Vendor commands run unlocked. Readback must check for a managed generation published - /// while the command was running, even when the plugin itself now looks current. - package func checkAfterHostCommand(store: StateStore) throws { - let native = route(store.scope) - try store.withReadLock(footprint: [native]) { - try requireScope(store) - let target = try store.nativeTarget(for: native) - try requireProjectAuthority(target.url, store: store) - guard try store.hasMaterializationReceipt(for: target) else { return } - let settings = "\(store.scope.rawValue)-scope Codex settings" - do { - let live = try TargetPrecondition(target.url) - guard live.exists, try store.materializationReceipt(for: target) != nil else { - throw CoreError.invalidState("private settings or their receipt are missing") - } - try live.validate() - } catch { - throw CoreError.invalidState( - "A private MCP materialization receipt for \(settings) no longer matches the live file. Reconcile the managed MCP settings and receipt before retrying host plugin sync." - ) - } - throw CoreError.invalidState( - "A private MCP materialization appeared in \(settings) during the host command. Review the managed MCP settings and plugin state before retrying host plugin sync." + package static func withCodexCommandLocks( + stores: [StateStore], _ command: () async -> Result + ) async throws -> Result { + guard !TransactionLockContext.isHeld else { + throw CoreError.invalidState("host commands require an unlocked StateStore") + } + let settings = try stores.map { store in + try Self.codex.requireScope(store) + let route = Self.codex.route(store.scope) + return ( + store, route, + try route.physicalDirectory(store.environment).appendingPathComponent(route.basename) ) } + let targets = Set(settings.map { $0.2 }).sorted { + $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) + } + let locks = try await CodexHostCommandLock.acquireForHost(targets) + defer { for lock in locks { lock.release() } } + try Task.checkCancellation() + for (store, route, expected) in settings { + try store.withReadLock(footprint: [route]) { + _ = try Self.codex.checkedTarget(store, forMutation: true, expected: expected) + } + } + try Task.checkCancellation() + return await command() } package func edit( @@ -90,7 +110,7 @@ package enum HostPluginConfigurationRoute { ) throws { try requireScope(store) try store.withLock(footprint: [route(store.scope)]) { - let target = try editableTarget(store) + let target = try checkedTarget(store, forMutation: true) let before = try TargetPrecondition.readingFile( target.url, maximumFileBytes: maximumFileBytes) guard let after = try transform(before.bytes), after != before.bytes else { return } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index a20157d..660e1f0 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -942,7 +942,7 @@ struct AbsentSharedRoot { } } -/// Synchronous, thread-confined admission. There is no lock acquisition inside a transaction. +/// Synchronous, thread-confined admission for scope and shared-resource locks. final class TransactionLockContext { private static let threadKey = "agents.core.transaction-lock-context" let scopeURL: URL @@ -962,6 +962,17 @@ final class TransactionLockContext { private var scopeDirectory: DirectoryHandle? private var scopeDescriptor: Int32? private var scopeLockIdentity: FileObjectIdentity? + private var codexCommandLocks: [Data: CodexHostCommandLock] = [:] + + /// The scope owns these leases through commit and recovery. Acquisition must never + /// wait because host commands take the same lock before entering a scope read. + func excludeCodexHostCommands(at target: URL) throws { + let key = Data(target.path.utf8) + if codexCommandLocks[key] == nil { + try requireWriterScope() + codexCommandLocks[key] = try CodexHostCommandLock.acquire(for: target, wait: false) + } + } init( store: StateStore, resources: [SharedResource], writable: Bool, requestedShared: Bool, @@ -999,7 +1010,10 @@ final class TransactionLockContext { throw CoreError.invalidState("nested scope operations cannot acquire transaction locks") } Thread.current.threadDictionary[Self.threadKey] = self - defer { Thread.current.threadDictionary.removeObject(forKey: Self.threadKey) } + defer { + codexCommandLocks.removeAll() + Thread.current.threadDictionary.removeObject(forKey: Self.threadKey) + } return try body() } diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index f8fc23e..b3e9535 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -136,6 +136,16 @@ extension StateStore { nativeArrays: record.nativeArrays) } + // Codex receipt publication and the vendor's unlocked settings command must be exclusive. + func excludeHostCommands(for path: String, at url: URL) throws { + let route = NativeTargetRoute.targetRoute(path) + guard route == .codexMCPUser || route == .codexMCPProject else { return } + guard let context = TransactionLockContext.current(self), context.writable else { + throw CoreError.invalidState("private Codex publication requires a held scope writer") + } + try context.excludeCodexHostCommands(at: url) + } + /// Under the caller's scope lock, preparation never calls a provider or renderer. package func preparePrivateMaterialization( _ target: MaterializationTarget, changingAccess: Bool = false, @@ -144,6 +154,9 @@ 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 TransactionLockContext.current(self)?.writable == true { + try excludeHostCommands(for: target.path, at: target.url) + } if let route = try TransactionPaths(store: self).coordinationRoute(for: target.path), try TransactionLockContext.current(self)?.absentRoot(for: route) != nil { diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift index 71a0ff9..d8f89fc 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift @@ -181,15 +181,17 @@ public enum HostPluginExecutor { let missing = observed?.installed != true let toggle = observed?.effective != enabled || observed?.explicit.map { $0 != enabled } == true - if !missing && !toggle { return report(.current) } if target.agent == .codex { - if toggle { try HostPluginConfigurationRoute.codex.checkEditable(store: store) } + try HostPluginConfigurationRoute.codex.checkReceipt( + store: store, forMutation: missing || toggle) // Codex CLI installation and marketplace registration write user settings. - if missing, target.scope == .project { - try HostPluginConfigurationRoute.codex.checkEditable( - store: StateStore(scope: .user, environment: locations.environment)) + if target.scope == .project { + try HostPluginConfigurationRoute.codex.checkReceipt( + store: StateStore(scope: .user, environment: locations.environment), + forMutation: missing) } } + if !missing && !toggle { return report(.current) } var commands: [Command] = [] var changes: [HostPluginConfigurationChange] = [] var edits: [HostPluginConfigurationChange] = [] @@ -341,40 +343,31 @@ public enum HostPluginExecutor { ? (target.scope == .user ? [InstallScope.user] : [.user, .project]).map { StateStore(scope: $0, environment: locations.environment) } : [] + let result: HostPluginCommandResult do { - for store in codexStores { - try HostPluginConfigurationRoute.codex.checkEditable(store: store) + if codexStores.isEmpty { + result = await runner.run(argv: command.argv, environment: locations.environment) + } else { + result = try await HostPluginConfigurationRoute.withCodexCommandLocks( + stores: codexStores + ) { + await runner.run(argv: command.argv, environment: locations.environment) + } } } catch CoreError.unsupported(let reason) { + current = plan(target, locations: locations) return finish(.unsupported, reason) + } catch is CancellationError { + return finish(.failed, "Host plugin synchronization was cancelled.") } catch { return finish(.failed, "Codex settings could not be verified before the host command.") } ran.append(command.argv) - let result = await runner.run(argv: command.argv, environment: locations.environment) - let readback: @Sendable () -> (Plan, String?) = { - let observed = plan(target, locations: locations) - do { - for store in codexStores { - try HostPluginConfigurationRoute.codex.checkAfterHostCommand(store: store) - } - } catch CoreError.invalidState(let reason) { - return (observed, reason) - } catch { - return ( - observed, - "Codex settings could not be verified after the host command. Check the managed MCP settings before retrying host plugin sync." - ) - } - return (observed, nil) - } - let reconciled = - Task.isCancelled ? await Task.detached(operation: readback).value : readback() - current = reconciled.0 - if let conflict = reconciled.1 { return finish(.failed, conflict) } if Task.isCancelled { + current = await Task.detached { plan(target, locations: locations) }.value return finish(.failed, "Host plugin synchronization was cancelled.") } + current = plan(target, locations: locations) switch result { case .success: if command.role == .install, current.preview.status.installed == true { installed = true } diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index b603d83..e9bef7d 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -1113,9 +1113,6 @@ package final class ArtifactAggregation: PreparedEvidence { components: [ComponentOutputEntry] = [], oldComponents: [ComponentOutputEntry] = [] ) 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) @@ -1132,6 +1129,31 @@ package final class ArtifactAggregation: PreparedEvidence { let target = contributions.first?.2 ?? components.first?.target ?? oldComponents.first?.target ?? priorTarget else { return } + 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: recordedOldBindings) : nil + let capture = try TargetPrecondition.readingFile(url) + targets[path] = try capture.evidence.capturingPublicationAccess() + fingerprints.append(try capture.evidence.displayEvidence(includeContent: false)) let format = components.first?.output.route.documentFormat ?? oldComponents.first?.output.route .documentFormat @@ -1302,28 +1324,6 @@ package final class ArtifactAggregation: PreparedEvidence { 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 - 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: recordedOldBindings) : nil let receiptArrays = try store.materializationReceipt(for: target)?.nativeArrays ?? [] let authority = previous.nativeAuthorities?.first { (try? $0.target.resolve(roots: roots).path) == path diff --git a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift index d0be0cc..b4e43f9 100644 --- a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift +++ b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift @@ -381,18 +381,7 @@ extension PrivateNativeCompositionTests { try fixture.write(#"[plugins."github@curated"]"# + "\nenabled = true\n", at: config) try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: config.path) try fixture.codexBundle("curated/github/1") - try fixture.declare( - """ - components: - - kind: mcpServer - name: service - agents: [codex] - transport: - kind: stdio - executable: fixture-mcp - environment: {TOKEN: {secret: token}} - - {kind: hostPlugin, name: github, pluginId: github@curated, enabled: false, agents: [codex]} - """, scope: .user) + try declareCodexService(in: fixture, pluginEnabled: false) let provider = NativeBindings() _ = try UpdateOperations.withPreparedUpdate( scope: .user, environment: fixture.environment, bindingProvider: provider @@ -415,40 +404,37 @@ extension PrivateNativeCompositionTests { } @Test(arguments: [false, true]) - func codexInstallDetectsPrivateReceiptPublishedDuringCommand(_ stale: Bool) async throws { + func codexInstallExcludesPrivatePublicationAndLeavesAValidSubsequentReceipt(_ partial: Bool) + async throws + { let fixture = try HostPluginFixture() let config = fixture.home.appendingPathComponent(".codex/config.toml") - try fixture.declare( - """ - components: - - kind: mcpServer - name: service - agents: [codex] - transport: - kind: stdio - executable: fixture-mcp - environment: {TOKEN: {secret: token}} - - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} - """, scope: .user) + let store = StateStore(scope: .user, environment: fixture.environment) + try declareCodexService(in: fixture) let provider = NativeBindings() let toggle = #"[plugins."github@curated"]"# + "\nenabled = true\n" let runner = RecordingHostRunner { argv, environment in guard argv == ["codex", "plugin", "add", "github@curated", "--json"] else { return .failed } do { - if !stale { - try fixture.write(toggle, at: config) - try FileManager.default.setAttributes( - [.posixPermissions: 0o600], ofItemAtPath: config.path) + let partialSettings = "[plugins." + if partial { try fixture.write(partialSettings, at: config) } + let busy = CoreError.invalidState( + "a host plugin command is currently modifying this configuration; retry after it completes" + ) + #expect(throws: busy) { + try UpdateOperations.withPreparedUpdate( + scope: .user, environment: environment, bindingProvider: provider + ) { try $0.apply() } } - _ = try UpdateOperations.withPreparedUpdate( - scope: .user, environment: environment, bindingProvider: provider - ) { try $0.apply() } - if stale { - let handle = try FileHandle(forWritingTo: config) - defer { try? handle.close() } - try handle.seekToEnd() - try handle.write(contentsOf: Data(("\n" + toggle).utf8)) + #expect(provider.calls.withLock { $0 } == 0) + let before = try? String(contentsOf: config, encoding: .utf8) + #expect(before == (partial ? partialSettings : nil)) + let receipt = try store.withReadLock(footprint: [.codexMCPUser]) { + try store.materializationReceipt(for: store.nativeTarget(for: .codexMCPUser)) } + #expect(receipt == nil) + try fixture.write(toggle, at: config) + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: config.path) try fixture.codexBundle("curated/github/1") return .success } catch { @@ -458,17 +444,88 @@ extension PrivateNativeCompositionTests { } let result = try await HostPluginExecutor.sync( scope: .user, apply: true, environment: fixture.environment, runner: runner) - #expect(result.first?.outcome == .failed) - #expect(result.first?.status.installed == true) + #expect(result.first?.outcome == .installed) #expect(result.first?.status.effectiveEnabled == true) #expect(await runner.calls.count == 1) - #expect(provider.calls.withLock { $0 } == 1) - let diagnostic = try #require(result.first?.diagnostic) - if stale { - #expect(diagnostic.contains("no longer matches the live file")) - } else { - #expect(diagnostic.contains("appeared") && diagnostic.contains("during the host command")) + #expect(try String(contentsOf: config, encoding: .utf8) == toggle) + + func applyManagedMCP() throws -> UUID { + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: fixture.environment, bindingProvider: provider + ) { try $0.apply() } + let bytes = try String(contentsOf: config, encoding: .utf8) + #expect(bytes.contains(toggle)) + #expect(bytes.contains(provider.secret)) + let inspection = try UpdateOperations.inspect(scope: .user, environment: fixture.environment) + let service = try #require( + inspection.components.first { $0.kind == .mcpServer && $0.name == "service" }) + #expect( + inspection.deployments.contains { + $0.ownerRecords.contains(service.record) && $0.location.path == config.path + && $0.privateMaterialization && $0.status == .current + }) + let receipt = try store.withReadLock(footprint: [.codexMCPUser]) { + try store.materializationReceipt(for: store.nativeTarget(for: .codexMCPUser)) + } + return try #require(receipt?.generation) } - #expect(diagnostic.contains("before retrying")) + + let first = try applyManagedMCP() + try declareCodexService(in: fixture, mcpArgument: "updated") + let second = try applyManagedMCP() + #expect(first != second) + #expect(try String(contentsOf: config, encoding: .utf8).contains("updated")) + #expect(provider.calls.withLock { $0 } == 2) + } + + @Test func staleCodexReceiptPreventsCurrentOrUnchangedReadback() async throws { + let fixture = try HostPluginFixture() + let config = fixture.home.appendingPathComponent(".codex/config.toml") + try declareCodexService(in: fixture) + try fixture.write(#"[plugins."github@curated"]"# + "\nenabled = true\n", at: config) + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: config.path) + try fixture.codexBundle("curated/github/1") + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: fixture.environment, bindingProvider: NativeBindings() + ) { try $0.apply() } + + let runner = RecordingHostRunner { _, _ in .failed } + let current = try HostPluginExecutor.preview(scope: .user, environment: fixture.environment) + #expect(current.first?.status.drift == .current) + let unchanged = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(unchanged.first?.outcome == .unchanged) + + let file = try FileHandle(forWritingTo: config) + try file.seekToEnd() + try file.write(contentsOf: Data("\n[analytics]\nenabled = false\n".utf8)) + try file.close() + let stale = try HostPluginExecutor.preview(scope: .user, environment: fixture.environment) + #expect(stale.first?.status.effectiveEnabled == true) + #expect(stale.first?.status.drift == .unsupported) + #expect(stale.first?.status.diagnostic?.contains("no longer matches the live file") == true) + let sync = try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + #expect(sync.first?.outcome == .unsupported) + #expect(sync.first?.diagnostic?.contains("no longer matches the live file") == true) + #expect(await runner.calls.isEmpty) + } + + private func declareCodexService( + in fixture: HostPluginFixture, pluginEnabled: Bool = true, mcpArgument: String = "serve" + ) throws { + try fixture.declare( + """ + components: + - kind: mcpServer + name: service + agents: [codex] + transport: + kind: stdio + executable: fixture-mcp + arguments: [\(mcpArgument)] + environment: {TOKEN: {secret: token}} + - {kind: hostPlugin, name: github, pluginId: github@curated, enabled: \(pluginEnabled), agents: [codex]} + """, scope: .user) } } From 200cba62d962da90b9d94e54568e5fca170dc662 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:49:54 +0800 Subject: [PATCH 06/10] fix: inherit Codex host command locks into child processes and cover readback --- Documentation/Architecture/Package.md | 11 +- Documentation/Architecture/State.md | 12 +- Sources/AgentsCore/CodexHostCommandLock.swift | 40 +++--- .../AgentsCore/HostPluginConfiguration.swift | 23 +++- .../AgentsCore/NativeTargetCoordination.swift | 2 +- Sources/AgentsCore/OwnedDuplexProcess.swift | 15 ++- .../HostPlugins/HostPluginCommandRunner.swift | 15 ++- .../HostPlugins/HostPluginExecutor.swift | 23 +++- Sources/CPlatform/DuplexProcess.c | 35 ++++- Sources/CPlatform/include/DuplexProcess.h | 6 +- .../OwnedDuplexProcessTests.swift | 48 +++++++ .../HostPluginExecutorTests.swift | 125 +++++++++++++++++- .../PrivateNativeCompositionTests.swift | 88 ++++++++++++ .../UpdateTransactionTests.swift | 11 +- Tests/StateTestProcess/main.swift | 8 ++ 15 files changed, 408 insertions(+), 54 deletions(-) create mode 100644 Tests/AgentsCoreTests/OwnedDuplexProcessTests.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 591fb98..d37e132 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -466,11 +466,12 @@ command. Cancellation preserves completed results. Codex and Antigravity project settings changes use recoverable native file publication. Codex uses the existing config coordination routes and defers to any private MCP materialization receipt on the same file. A separate per-target advisory lock -excludes private Codex receipt publication while a host command runs. Codex -preflight and readback verify existing receipt evidence, including on no-op -syncs. Project settings edits require a physical destination within project -authority. Claude Code uses host commands with its selected user, project, or -local scope. +excludes private Codex receipt publication through command readback. The Codex +child inherits the locked open file description and retains exclusion if it +outlives the caller. Codex preflight and readback verify existing receipt +evidence, including on no-op syncs. Project settings edits require a physical +destination within project authority. Claude Code uses host commands with its +selected user, project, or local scope. The manifest's `hostPlugin` declaration takes explicit recipients and either a marketplace ID or one source-backed bundle. Source-backed inspection reads a diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index e6afa98..108a8d7 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -628,11 +628,13 @@ changes cause freshness conflicts rather than overwriting client siblings. Codex vendor commands and private receipt publishers share a separate advisory lock at `.agents-host-commands/config.toml.lock` under the physical settings -parent. The host takes it before a brief scope read and holds it through the -command with scope and shared-resource locks released. Managed writers try the -host lock without waiting and retain it through commit or rollback. A contended -writer stops before publishing settings or a receipt and can retry after the -host command completes. +parent. The host takes it before a brief scope read, runs the command with scope +and shared-resource locks released, and keeps the advisory lock through +readback. The Codex child inherits the locked open file description, so a child +that survives its parent continues to exclude writers until the last copy +closes. Managed writers try the host lock without waiting and retain it through +commit or rollback. A contended writer stops before publishing settings or a +receipt and can retry after the host lock is released. E supplies the complete new/old deployment footprint and redacted composition; F supplies exact owned-region edits and route semantics. These Core registrations diff --git a/Sources/AgentsCore/CodexHostCommandLock.swift b/Sources/AgentsCore/CodexHostCommandLock.swift index 1ba9c3a..9d801f1 100644 --- a/Sources/AgentsCore/CodexHostCommandLock.swift +++ b/Sources/AgentsCore/CodexHostCommandLock.swift @@ -1,5 +1,4 @@ import CPlatform -import Dispatch import Foundation import Synchronization @@ -7,18 +6,25 @@ import Synchronization /// so successive commands and transactions always contend on the same inode. final class CodexHostCommandLock: Sendable { private static let directoryName = ".agents-host-commands" + private static let contention = CoreError.invalidState( + "a host plugin command is currently modifying this configuration; retry after it completes") + @TaskLocal static var contentionObserverForTesting: (@Sendable () -> Void)? + private let descriptor: Atomic private init(descriptor: Int32) { self.descriptor = Atomic(descriptor) } deinit { release() } + var fileDescriptor: Int32 { descriptor.load(ordering: .relaxed) } + func release() { + // A surviving child may own this open file description. Close, never unlock. let open = descriptor.exchange(-1, ordering: .relaxed) if open >= 0 { close(open) } } - static func acquire(for target: URL, wait: Bool) throws -> CodexHostCommandLock { + static func acquire(for target: URL) throws -> CodexHostCommandLock { let url = target.deletingLastPathComponent() let parent: DirectoryHandle do { @@ -58,15 +64,10 @@ final class CodexHostCommandLock: Sendable { guard access.identity.kind == S_IFREG else { throw CoreError.unsafePath("the Codex host command lock must be a regular file") } - let mode = wait ? LOCK_EX : LOCK_EX | LOCK_NB - while platform_flock(descriptor, mode) != 0 { + while platform_flock(descriptor, LOCK_EX | LOCK_NB) != 0 { let failure = errno if failure == EINTR { continue } - if !wait, failure == EWOULDBLOCK || failure == EAGAIN { - throw CoreError.invalidState( - "a host plugin command is currently modifying this configuration; retry after it completes" - ) - } + if failure == EWOULDBLOCK || failure == EAGAIN { throw contention } throw CoreError.invalidState("cannot acquire the Codex host command lock") } guard try parent.info(directoryName).map(FileObjectIdentity.init) == directoryAccess.identity, @@ -76,15 +77,22 @@ final class CodexHostCommandLock: Sendable { return lock } - /// Blocking advisory lock acquisition must not occupy a Swift cooperative executor thread. static func acquireForHost(_ targets: [URL]) async throws -> [CodexHostCommandLock] { - try await withCheckedThrowingContinuation { continuation in - DispatchQueue.global().async { - continuation.resume( - with: Result { - try targets.map { try acquire(for: $0, wait: true) } - }) + while true { + try Task.checkCancellation() + var locks: [CodexHostCommandLock] = [] + do { + for target in targets { + try Task.checkCancellation() + locks.append(try acquire(for: target)) + } + return locks + } catch { + for lock in locks { lock.release() } + guard (error as? CoreError) == contention else { throw error } } + contentionObserverForTesting?() + try await Task.sleep(for: .milliseconds(20)) } } } diff --git a/Sources/AgentsCore/HostPluginConfiguration.swift b/Sources/AgentsCore/HostPluginConfiguration.swift index b7af08d..15ce2bb 100644 --- a/Sources/AgentsCore/HostPluginConfiguration.swift +++ b/Sources/AgentsCore/HostPluginConfiguration.swift @@ -1,9 +1,25 @@ import Foundation +import Synchronization /// Settings edits use the native file's coordination and journal. Vendor commands run separately. package enum HostPluginConfigurationRoute { case codex, antigravityProject + private final class CommandDescriptors: Sendable { + let values: Mutex<[Int32]> + init(_ descriptors: [Int32]) { values = Mutex(descriptors) } + } + + @TaskLocal private static var commandDescriptors: CommandDescriptors? + + /// Borrow the descriptors during spawn, including when a runner delegates work to a child task. + package static func withCodexCommandDescriptors( + _ body: ([Int32]) throws -> Result + ) rethrows -> Result { + guard let commandDescriptors else { return try body([]) } + return try commandDescriptors.values.withLock { try body($0) } + } + private func route(_ scope: InstallScope) -> NativeTargetRoute { switch self { case .codex: return scope == .user ? .codexMCPUser : .codexMCPProject @@ -100,7 +116,12 @@ package enum HostPluginConfigurationRoute { } } try Task.checkCancellation() - return await command() + let descriptors = CommandDescriptors(locks.map(\.fileDescriptor)) + // An inherited task-local binding can live past this scope. Clear it before closing the FDs. + defer { descriptors.values.withLock { $0.removeAll() } } + return await $commandDescriptors.withValue(descriptors) { + await command() + } } package func edit( diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 660e1f0..fbd97c4 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -970,7 +970,7 @@ final class TransactionLockContext { let key = Data(target.path.utf8) if codexCommandLocks[key] == nil { try requireWriterScope() - codexCommandLocks[key] = try CodexHostCommandLock.acquire(for: target, wait: false) + codexCommandLocks[key] = try CodexHostCommandLock.acquire(for: target) } } diff --git a/Sources/AgentsCore/OwnedDuplexProcess.swift b/Sources/AgentsCore/OwnedDuplexProcess.swift index d01a63a..286dc61 100644 --- a/Sources/AgentsCore/OwnedDuplexProcess.swift +++ b/Sources/AgentsCore/OwnedDuplexProcess.swift @@ -6,14 +6,18 @@ package struct DuplexProcessConfiguration: Sendable { package var arguments: [String] package var directory: URL package var environment: [String: String] + /// Borrowed through spawn and mapped to descriptors starting at 3 in the child. + package var inheritedDescriptors: [Int32] package init( - executable: String, arguments: [String], directory: URL, environment: [String: String] + executable: String, arguments: [String], directory: URL, environment: [String: String], + inheritedDescriptors: [Int32] = [] ) { self.executable = executable self.arguments = arguments self.directory = directory self.environment = environment + self.inheritedDescriptors = inheritedDescriptors } } @@ -47,6 +51,7 @@ package final class OwnedDuplexProcess: @unchecked Sendable { 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.inheritedDescriptors.allSatisfy({ $0 >= 0 }), configuration.environment.allSatisfy({ !$0.key.isEmpty && !$0.key.contains("=") && valid($0.key) && valid($0.value) }) @@ -102,9 +107,11 @@ package final class OwnedDuplexProcess: @unchecked Sendable { var pid: pid_t = 0 var fds: [Int32] = [-1, -1, -1] let result = withExtendedLifetime(workingDirectory) { - platform_duplex_spawn( - &pid, executable, arguments, environment, configuration.directory.path, - workingDirectory?.descriptor ?? -1, &fds) + configuration.inheritedDescriptors.withUnsafeBufferPointer { inherited in + platform_duplex_spawn( + &pid, executable, arguments, environment, configuration.directory.path, + workingDirectory?.descriptor ?? -1, inherited.baseAddress, inherited.count, &fds) + } } guard result == 0 else { throw DuplexProcessError.launchFailed } identifier = pid diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginCommandRunner.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginCommandRunner.swift index b66fbb2..bbbe8be 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginCommandRunner.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginCommandRunner.swift @@ -30,12 +30,19 @@ public struct ProcessHostPluginCommandRunner: HostPluginCommandRunner { && !directory.boolValue && FileManager.default.isExecutableFile(atPath: path) }) else { return .cliUnavailable } - let process: OwnedDuplexProcess - do { - process = try OwnedDuplexProcess( + func spawn(inheriting descriptors: [Int32]) throws -> OwnedDuplexProcess { + try OwnedDuplexProcess( .init( executable: executable, arguments: Array(argv.dropFirst()), - directory: environment.projectDirectory, environment: variables)) + directory: environment.projectDirectory, environment: variables, + inheritedDescriptors: descriptors)) + } + let process: OwnedDuplexProcess + do { + process = + try executable == "codex" + ? HostPluginConfigurationRoute.withCodexCommandDescriptors(spawn) + : spawn(inheriting: []) } catch { return .failed } process.closeInput() diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift index d8f89fc..b5c71f7 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginExecutor.swift @@ -4,6 +4,8 @@ import NativeDocuments /// Read-only host inventory and explicit, independently reconciled plugin synchronization. public enum HostPluginExecutor { + @TaskLocal static var beforeCommandReadbackForTesting: (@Sendable () async -> Void)? + public static func inspect( scope: InstallScope = .project, agents: [AgentID]? = nil, environment: RuntimeEnvironment = .init(), includeUnmanaged: Bool = true @@ -343,15 +345,24 @@ public enum HostPluginExecutor { ? (target.scope == .user ? [InstallScope.user] : [.user, .project]).map { StateStore(scope: $0, environment: locations.environment) } : [] - let result: HostPluginCommandResult + func runAndReadBack() async -> (HostPluginCommandResult, Plan) { + let result = await runner.run(argv: command.argv, environment: locations.environment) + await beforeCommandReadbackForTesting?() + let observed = + Task.isCancelled + ? await Task.detached { plan(target, locations: locations) }.value + : plan(target, locations: locations) + return (result, observed) + } + let observation: (HostPluginCommandResult, Plan) do { if codexStores.isEmpty { - result = await runner.run(argv: command.argv, environment: locations.environment) + observation = await runAndReadBack() } else { - result = try await HostPluginConfigurationRoute.withCodexCommandLocks( + observation = try await HostPluginConfigurationRoute.withCodexCommandLocks( stores: codexStores ) { - await runner.run(argv: command.argv, environment: locations.environment) + await runAndReadBack() } } } catch CoreError.unsupported(let reason) { @@ -363,11 +374,11 @@ public enum HostPluginExecutor { return finish(.failed, "Codex settings could not be verified before the host command.") } ran.append(command.argv) + let (result, observed) = observation + current = observed if Task.isCancelled { - current = await Task.detached { plan(target, locations: locations) }.value return finish(.failed, "Host plugin synchronization was cancelled.") } - current = plan(target, locations: locations) switch result { case .success: if command.role == .install, current.preview.status.installed == true { installed = true } diff --git a/Sources/CPlatform/DuplexProcess.c b/Sources/CPlatform/DuplexProcess.c index 79d1a81..7d2c74d 100644 --- a/Sources/CPlatform/DuplexProcess.c +++ b/Sources/CPlatform/DuplexProcess.c @@ -1,5 +1,6 @@ #define _GNU_SOURCE 1 #include "CPlatform.h" +#include #include #include #if defined(__APPLE__) @@ -15,12 +16,33 @@ int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[], char *const environment[], const char *directory, - int directory_descriptor, int descriptors[3]) { + int directory_descriptor, const int inherited_fds[], + size_t inherited_count, 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; + if (inherited_count > INT_MAX - 3 || inherited_count > SIZE_MAX / sizeof(int) || + (inherited_count && !inherited_fds)) return EINVAL; + for (size_t i = 0; i < inherited_count; i++) { + if (inherited_fds[i] < 0) return EINVAL; + if (fcntl(inherited_fds[i], F_GETFD) < 0) return errno; + } + + // Sources must sit above every destination, so dup2 cannot overwrite a later + // source and always clears CLOEXEC on its destination in the child only. + int first_temporary = 3 + (int)inherited_count; + int *inherited_sources = inherited_count ? malloc(inherited_count * sizeof(int)) : NULL; + if (inherited_count && !inherited_sources) return ENOMEM; + size_t duplicated = 0; int pipes[6] = {-1,-1,-1,-1,-1,-1}; int result = 0; + for (; duplicated < inherited_count; duplicated++) { + int source; + do { source = fcntl(inherited_fds[duplicated], F_DUPFD_CLOEXEC, first_temporary); } + while (source < 0 && errno == EINTR); + if (source < 0) { result = errno; goto cleanup; } + inherited_sources[duplicated] = source; + } for (int i = 0; i < 6; i += 2) { #if defined(__APPLE__) if (pipe(&pipes[i]) < 0) { result = errno; goto cleanup; } @@ -31,8 +53,8 @@ int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[] 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 (pipes[j] < first_temporary) { + int replacement = fcntl(pipes[j], F_DUPFD_CLOEXEC, first_temporary); if (replacement < 0) { result = errno; goto cleanup; } close(pipes[j]); pipes[j] = replacement; } @@ -68,8 +90,11 @@ int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[] 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)); + for (size_t i = 0; i < inherited_count; i++) { + CHECK(posix_spawn_file_actions_adddup2(&actions, inherited_sources[i], 3 + (int)i)); + } #if !defined(__APPLE__) - CHECK(posix_spawn_file_actions_addclosefrom_np(&actions, 3)); + CHECK(posix_spawn_file_actions_addclosefrom_np(&actions, first_temporary)); #endif // Parent ends are nonblocking; child standard streams retain ordinary blocking I/O. for (int i = 0; i < 3; i++) { @@ -92,6 +117,8 @@ int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[] #undef CHECK cleanup: for (int i = 0; i < 6; i++) if (pipes[i] >= 0) close(pipes[i]); + for (size_t i = 0; i < duplicated; i++) close(inherited_sources[i]); + free(inherited_sources); return result; } diff --git a/Sources/CPlatform/include/DuplexProcess.h b/Sources/CPlatform/include/DuplexProcess.h index 8115dbe..40682cc 100644 --- a/Sources/CPlatform/include/DuplexProcess.h +++ b/Sources/CPlatform/include/DuplexProcess.h @@ -4,11 +4,13 @@ #include #include -// Owns a new process group. Only descriptors 0...2 survive exec. +// Owns a new process group. Inherited descriptors are borrowed and mapped to 3+i. +// Only standard streams and the explicitly inherited descriptors 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 directory_descriptor, int descriptors[3]); + int directory_descriptor, const int inherited_fds[], + size_t inherited_count, 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. diff --git a/Tests/AgentsCoreTests/OwnedDuplexProcessTests.swift b/Tests/AgentsCoreTests/OwnedDuplexProcessTests.swift new file mode 100644 index 0000000..65420d2 --- /dev/null +++ b/Tests/AgentsCoreTests/OwnedDuplexProcessTests.swift @@ -0,0 +1,48 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +struct OwnedDuplexProcessTests { + @Test(arguments: [false, true]) + func execInheritsOnlyRequestedDescriptors(_ inherit: Bool) async throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let firstURL = root.appendingPathComponent("first") + let secondURL = root.appendingPathComponent("second") + let first = open(firstURL.path, O_CREAT | O_RDWR | O_CLOEXEC, 0o600) + try #require(first >= 0) + defer { close(first) } + let second = open(secondURL.path, O_CREAT | O_RDWR | O_CLOEXEC, 0o600) + try #require(second >= 0) + defer { close(second) } + let unrelated = fcntl(first, F_DUPFD, 64) + try #require(unrelated >= 64) + defer { close(unrelated) } + + let script = + inherit + ? "test ! -e /dev/fd/$1 && printf first >&3 && printf second >&4" + : "test ! -e /dev/fd/$1 && test ! -e /dev/fd/3 && test ! -e /dev/fd/4" + let process = try OwnedDuplexProcess( + .init( + executable: "/bin/sh", arguments: ["-c", script, "sh", String(unrelated)], + directory: root, environment: [:], inheritedDescriptors: inherit ? [first, second] : [])) + #expect(fcntl(first, F_GETFD) == FD_CLOEXEC) + #expect(fcntl(second, F_GETFD) == FD_CLOEXEC) + + let deadline = ContinuousClock.now + .seconds(5) + var exit = process.exitIfFinished() + while exit == nil, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + exit = process.exitIfFinished() + } + #expect(await process.finish(grace: .zero, terminate: .zero, killWait: .seconds(2))) + guard case .status(0) = exit else { + Issue.record("Child did not confirm its descriptor layout: \(String(describing: exit))") + return + } + #expect(try String(contentsOf: firstURL, encoding: .utf8) == (inherit ? "first" : "")) + #expect(try String(contentsOf: secondURL, encoding: .utf8) == (inherit ? "second" : "")) + } +} diff --git a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift index e649dce..23aaecd 100644 --- a/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift +++ b/Tests/AgentsUpdatesTests/HostPluginExecutorTests.swift @@ -1,10 +1,12 @@ -import AgentsCore import AgentsManifest -import AgentsUpdates import Foundation import StateTestSupport +import Synchronization import Testing +@testable import AgentsCore +@testable import AgentsUpdates + @Suite("Host plugin execution") struct HostPluginExecutorTests { @Test func dryRunAndOrdinaryUpdateDoNotInvokeOrWriteHostState() async throws { @@ -682,6 +684,125 @@ extension HostPluginExecutorTests { #expect(result.last?.diagnostic?.contains("cancelled") == true) #expect(await runner.calls == [["codex", "plugin", "add", "second@work", "--json"]]) } + + @Test(arguments: [false, true]) + func codexSyncHoldsCommandLocksThroughReadbackAndCancelsWaiters(_ cancelHolder: Bool) async throws + { + let fixture = try HostPluginFixture() + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} + """, scope: .user) + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: second, pluginId: second@work, agents: [codex]} + """) + let runner = RecordingHostRunner { argv, _ in + guard argv.count == 5 else { return .failed } + do { + if argv[3] == "github@curated" { + try fixture.codexBundle("curated/github/1") + try fixture.write( + #"[plugins."github@curated"]"# + "\nenabled = true\n", + at: fixture.home.appendingPathComponent(".codex/config.toml")) + } else { + try fixture.codexBundle("work/second/1") + try fixture.write( + #"[plugins."second@work"]"# + "\nenabled = true\n", + at: fixture.project.appendingPathComponent(".codex/config.toml")) + } + return .success + } catch { + Issue.record(error) + return .failed + } + } + let gate = HostReadbackGate() + let holder = Task { + try await HostPluginExecutor.$beforeCommandReadbackForTesting.withValue({ await gate.pause() } + ) { + try await HostPluginExecutor.sync( + scope: .user, apply: true, environment: fixture.environment, runner: runner) + } + } + defer { + holder.cancel() + Task { await gate.resume() } + } + try await waitForHostSync { await gate.isPaused } + if cancelHolder { holder.cancel() } + + let contended = Mutex(false) + let cancelled = Mutex(false) + let interrupted = Task { + defer { cancelled.withLock { $0 = true } } + return try await CodexHostCommandLock.$contentionObserverForTesting.withValue({ + contended.withLock { $0 = true } + }) { + try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + } + } + defer { interrupted.cancel() } + try await waitForHostSync { contended.withLock { $0 } } + interrupted.cancel() + try await waitForHostSync(timeout: .seconds(2)) { cancelled.withLock { $0 } } + let cancelledResult = try await interrupted.value + #expect(cancelledResult.first?.outcome == .failed) + #expect(cancelledResult.first?.diagnostic?.contains("cancelled") == true) + #expect(cancelledResult.first?.commandsRun.isEmpty == true) + + let nextContended = Mutex(false) + let next = Task { + try await CodexHostCommandLock.$contentionObserverForTesting.withValue({ + nextContended.withLock { $0 = true } + }) { + try await HostPluginExecutor.sync( + apply: true, environment: fixture.environment, runner: runner) + } + } + defer { next.cancel() } + try await waitForHostSync { nextContended.withLock { $0 } } + #expect(await runner.calls == [["codex", "plugin", "add", "github@curated", "--json"]]) + await gate.resume() + + let first = try await holder.value + #expect(first.first?.outcome == (cancelHolder ? .failed : .installed)) + #expect(first.first?.status.effectiveEnabled == true) + let second = try await next.value + #expect(second.first?.outcome == .installed) + #expect(await runner.calls.last == ["codex", "plugin", "add", "second@work", "--json"]) + } +} + +private func waitForHostSync( + timeout: Duration = .seconds(10), until ready: () async -> Bool +) async throws { + let deadline = ContinuousClock.now + timeout + while ContinuousClock.now < deadline { + if await ready() { return } + try await Task.sleep(for: .milliseconds(10)) + } + try #require(await ready()) +} + +private actor HostReadbackGate { + private var release: CheckedContinuation? + private var resumed = false + var isPaused: Bool { release != nil } + + func pause() async { + guard !resumed else { return } + await withCheckedContinuation { release = $0 } + } + + func resume() { + resumed = true + release?.resume() + release = nil + } } private actor CancellationHostRunner: HostPluginCommandRunner { diff --git a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift index b4e43f9..76948e6 100644 --- a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift +++ b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsUpdates import Foundation +import StateTestSupport import Synchronization import Testing @@ -478,6 +479,93 @@ extension PrivateNativeCompositionTests { #expect(provider.calls.withLock { $0 } == 2) } + @Test func survivingCodexProcessExcludesPrivatePublicationAfterCallerExit() async throws { + let fixture = try HostPluginFixture() + try declareCodexService(in: fixture) + try fixture.declare( + """ + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} + """) + let config = fixture.home.appendingPathComponent(".codex/config.toml") + let vendor = fixture.root.appendingPathComponent("bin/codex") + let ready = fixture.home.appendingPathComponent("vendor-ready") + let release = fixture.home.appendingPathComponent("vendor-release") + let toggle = #"[plugins."github@curated"]"# + "\nenabled = true\n" + try fixture.write( + """ + #!/bin/sh + set -eu + [ "$*" = "plugin add github@curated --json" ] + : >&3 + : >&4 + : > "$HOME/vendor-ready" + steps=0 + while [ ! -f "$HOME/vendor-release" ]; do + [ -d "$HOME" ] && [ "$steps" -lt 600 ] || exit 1 + steps=$((steps + 1)) + /bin/sleep 0.05 + done + umask 077 + printf '%s\\n' '[plugins."github@curated"]' 'enabled = true' > "$HOME/.codex/config.toml" + + """, at: vendor) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: vendor.path) + let caller = try launch(at: fixture.root, arguments: ["codex-host-sync"]) + defer { + try? Data().write(to: release) + if caller.isRunning { terminate(caller) } + } + try ProcessWait.marker(ready, child: caller, root: fixture.root, timeout: 15) + try ProcessWait.terminate(caller, timeout: 5) + #expect(caller.terminationReason == .uncaughtSignal) + #expect(caller.terminationStatus == SIGKILL) + + let provider = NativeBindings() + let busy = CoreError.invalidState( + "a host plugin command is currently modifying this configuration; retry after it completes") + func applyManagedMCP() throws { + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: fixture.environment, bindingProvider: provider + ) { try $0.apply() } + } + let store = StateStore(scope: .user, environment: fixture.environment) + func receipt() throws -> MaterializationReceipt? { + try store.withReadLock(footprint: [.codexMCPUser]) { + try store.materializationReceipt(for: store.nativeTarget(for: .codexMCPUser)) + } + } + + #expect(throws: busy) { try applyManagedMCP() } + #expect(try receipt() == nil) + #expect(provider.calls.withLock { $0 } == 0) + #expect(!FileManager.default.fileExists(atPath: config.path)) + + try Data().write(to: release) + let deadline = ContinuousClock.now + .seconds(5) + while true { + do { + try applyManagedMCP() + break + } catch let error as CoreError where error == busy && ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(20)) + } + } + #expect(try receipt() != nil) + try HostPluginConfigurationRoute.codex.checkReceipt(store: store, forMutation: false) + let settings = try String(contentsOf: config, encoding: .utf8) + #expect(settings.contains(toggle)) + #expect(settings.contains(provider.secret)) + let inspection = try UpdateOperations.inspect(scope: .user, environment: fixture.environment) + let service = try #require( + inspection.components.first { $0.kind == .mcpServer && $0.name == "service" }) + #expect( + inspection.deployments.contains { + $0.ownerRecords.contains(service.record) && $0.location.path == config.path + && $0.privateMaterialization && $0.status == .current + }) + } + @Test func staleCodexReceiptPreventsCurrentOrUnchangedReadback() async throws { let fixture = try HostPluginFixture() let config = fixture.home.appendingPathComponent(".codex/config.toml") diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index eb9792f..8fbbcd3 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -252,6 +252,11 @@ private let committedPoints = [ ].map(\.name) func launch(_ fixture: UpdateFixture, command: String, argument: String) throws -> Process { + try launch( + at: fixture.root, arguments: [command, argument, "--scope", fixture.store.scope.rawValue]) +} + +func launch(at root: URL, arguments: [String]) throws -> Process { var directory = Bundle(for: UpdateTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), @@ -259,10 +264,8 @@ func launch(_ fixture: UpdateFixture, command: String, argument: String) throws { directory.deleteLastPathComponent() } let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") - process.arguments = [ - fixture.root.path, command, argument, "--scope", fixture.store.scope.rawValue, - ] - let scratch = fixture.root.appendingPathComponent("process-temporary") + process.arguments = [root.path] + arguments + let scratch = root.appendingPathComponent("process-temporary") try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true) var environment = ProcessInfo.processInfo.environment environment["TMPDIR"] = scratch.path + "/" diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index f8b7723..3b014fe 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -10,6 +10,14 @@ import Synchronization let arguments = CommandLine.arguments let root = URL(fileURLWithPath: arguments[1]) +if arguments[2] == "codex-host-sync" { + let environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), + environment: ["PATH": root.appendingPathComponent("bin").path]) + let result = try await HostPluginExecutor.sync(apply: true, environment: environment) + exit(result.first?.outcome == .installed ? EXIT_SUCCESS : EXIT_FAILURE) +} let scopeIndex = arguments.firstIndex(of: "--scope") let scope: InstallScope = scopeIndex.flatMap { InstallScope(rawValue: arguments[$0 + 1]) } ?? .project From 5d4aaf5d1da0b0909ad4a0e6fc40a06b9ef92b5c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:10:32 +0800 Subject: [PATCH 07/10] docs: qualify OwnedDuplexProcess inherited descriptor behavior in Package.md --- Documentation/Architecture/Package.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index d37e132..8ff1ec7 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -178,8 +178,8 @@ 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, +spawn closes nonstandard child descriptors except explicitly inherited 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 From 8697b99f294195885029d0a9657336bedf2a99bb Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:21:50 +0800 Subject: [PATCH 08/10] chore: set release version to 0.3.2 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92077e7..dce8e22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased -## 0.4.0 +## 0.3.2 ### Added From a1ee984c1dd89b933c1365411f8c4e3e04cdfc42 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:47:18 +0800 Subject: [PATCH 09/10] docs: document native document node budget scaling --- Documentation/Architecture/NativeDocuments.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Documentation/Architecture/NativeDocuments.md b/Documentation/Architecture/NativeDocuments.md index 487b991..c54aeb6 100644 --- a/Documentation/Architecture/NativeDocuments.md +++ b/Documentation/Architecture/NativeDocuments.md @@ -88,7 +88,11 @@ 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 +traversal and progress callbacks consume additional work. Callers configuring +`NativeDocumentBudget` must scale `nodes` with `maximumBytes` (strictly above +`4 * maximumBytes + 1` plus traversal work, rather than a flat constant below +that expansion) and exercise parsers at realistic host-configuration byte +scales. The progress callback checks the same cancellation source and budget between parser work intervals. All parser/tree handles are synchronously released on every exit. From 55eb06b8b5de3203f2beb7e22bd894c1ecae350d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:10:47 +0800 Subject: [PATCH 10/10] fix: defer Codex host command lock directory creation until commit --- Sources/AgentsCore/CodexHostCommandLock.swift | 19 +++++++++++++++++++ Sources/AgentsCore/FileTransaction.swift | 7 ++++++- .../AgentsCore/NativeTargetCoordination.swift | 9 ++++++--- .../AgentsCore/PrivateMaterialization.swift | 6 +++--- 4 files changed, 34 insertions(+), 7 deletions(-) diff --git a/Sources/AgentsCore/CodexHostCommandLock.swift b/Sources/AgentsCore/CodexHostCommandLock.swift index 9d801f1..5a9ae2e 100644 --- a/Sources/AgentsCore/CodexHostCommandLock.swift +++ b/Sources/AgentsCore/CodexHostCommandLock.swift @@ -38,6 +38,25 @@ final class CodexHostCommandLock: Sendable { parent = existing } } + return try acquire(in: parent, url: url, target: target) + } + + /// Acquires the command lock only when the settings parent already exists, + /// avoiding directory creation during preparation before precondition checks. + static func acquireIfParentExists(for target: URL) throws -> CodexHostCommandLock? { + let url = target.deletingLastPathComponent() + let parent: DirectoryHandle + do { + parent = try DirectoryHandle(at: url, reportMissing: true) + } catch CoreError.notFound { + return nil + } + return try acquire(in: parent, url: url, target: target) + } + + private static func acquire( + in parent: DirectoryHandle, url: URL, target: URL + ) throws -> CodexHostCommandLock { _ = try FileAccessEvidence.requireNonReplaceableDirectory( descriptor: parent.descriptor, protectingOwner: geteuid()) if mkdirat(parent.descriptor, directoryName, 0o700) != 0, errno != EEXIST { diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 7d2b8ce..ef817b2 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -474,7 +474,8 @@ package final class FileTransaction { package func commit() throws { guard !requests.isEmpty else { return } for request in requests where request.security.replacement == .privateMaterialization { - try store.excludeHostCommands(for: request.path, at: request.evidence.physicalURL) + try store.excludeHostCommands( + for: request.path, at: request.evidence.physicalURL, createParent: false) } let shared = try requests.filter { try TransactionPaths(store: store).coordinationRoute(for: $0.path) != nil @@ -505,6 +506,10 @@ package final class FileTransaction { for request in requests { try request.evidence.validate() } try validateOverlap() let session = try makeSession(directory) + for request in requests where request.security.replacement == .privateMaterialization { + try store.excludeHostCommands( + for: request.path, at: request.evidence.physicalURL, createParent: true) + } outcome.journalID = session.journal.id do { try session.persist(.created) diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index fbd97c4..461019b 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -966,11 +966,14 @@ final class TransactionLockContext { /// The scope owns these leases through commit and recovery. Acquisition must never /// wait because host commands take the same lock before entering a scope read. - func excludeCodexHostCommands(at target: URL) throws { + func excludeCodexHostCommands(at target: URL, createParent: Bool = true) throws { let key = Data(target.path.utf8) - if codexCommandLocks[key] == nil { - try requireWriterScope() + guard codexCommandLocks[key] == nil else { return } + try requireWriterScope() + if createParent { codexCommandLocks[key] = try CodexHostCommandLock.acquire(for: target) + } else if let lock = try CodexHostCommandLock.acquireIfParentExists(for: target) { + codexCommandLocks[key] = lock } } diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift index b3e9535..6e12b43 100644 --- a/Sources/AgentsCore/PrivateMaterialization.swift +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -137,13 +137,13 @@ extension StateStore { } // Codex receipt publication and the vendor's unlocked settings command must be exclusive. - func excludeHostCommands(for path: String, at url: URL) throws { + func excludeHostCommands(for path: String, at url: URL, createParent: Bool = true) throws { let route = NativeTargetRoute.targetRoute(path) guard route == .codexMCPUser || route == .codexMCPProject else { return } guard let context = TransactionLockContext.current(self), context.writable else { throw CoreError.invalidState("private Codex publication requires a held scope writer") } - try context.excludeCodexHostCommands(at: url) + try context.excludeCodexHostCommands(at: url, createParent: createParent) } /// Under the caller's scope lock, preparation never calls a provider or renderer. @@ -155,7 +155,7 @@ extension StateStore { try TransactionPaths(store: self).path(for: target.url) == target.path else { throw CoreError.invalidState("materialization target belongs to another scope") } if TransactionLockContext.current(self)?.writable == true { - try excludeHostCommands(for: target.path, at: target.url) + try excludeHostCommands(for: target.path, at: target.url, createParent: false) } if let route = try TransactionPaths(store: self).coordinationRoute(for: target.path), try TransactionLockContext.current(self)?.absentRoot(for: route) != nil