From d3649defa0539ef339fba14b52f3e9d24619f776 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:28:53 +0800 Subject: [PATCH 1/5] fix: support semantic version dependencies on Core --- CHANGELOG.md | 7 +++++++ Package.resolved | 5 +++-- Package.swift | 4 +--- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c2d228..46cfefd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## 0.3.1 + +### Fixed + +- Swift packages can depend on Core by semantic version. Core uses the published + MCP Swift SDK 0.12.1 release. + ## 0.3.0 ### Added diff --git a/Package.resolved b/Package.resolved index 0438c2e..0acfcde 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "e52552c8d5747be8dcb02a8ace8ba7f8b39ac4605c24605c1811b3ccd827f09d", + "originHash" : "992769318673dd8324e4cd71c30839fce3031f7dd149151a5bd5fe4208ed0861", "pins" : [ { "identity" : "eventsource", @@ -87,7 +87,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/modelcontextprotocol/swift-sdk.git", "state" : { - "revision" : "a0ae212ebf6eab5f754c3129608bc5557637e605" + "revision" : "a0ae212ebf6eab5f754c3129608bc5557637e605", + "version" : "0.12.1" } }, { diff --git a/Package.swift b/Package.swift index 66bfd7a..5b82c90 100644 --- a/Package.swift +++ b/Package.swift @@ -16,9 +16,7 @@ let package = Package( .library(name: "AgentsUpdates", targets: ["AgentsUpdates"]), ], dependencies: [ - .package( - url: "https://github.com/modelcontextprotocol/swift-sdk.git", - revision: "a0ae212ebf6eab5f754c3129608bc5557637e605"), + .package(url: "https://github.com/modelcontextprotocol/swift-sdk.git", exact: "0.12.1"), .package(url: "https://github.com/apple/swift-crypto.git", from: "5.0.0"), .package(url: "https://github.com/jpsim/Yams", exact: "6.2.2"), .package(url: "https://github.com/swiftlang/swift-markdown.git", from: "0.9.0"), From 7cb9385303848981f0dab79b446e18bd407dbabd Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:57:26 +0800 Subject: [PATCH 2/5] fix: preserve subprocess cleanup on cancellation --- CHANGELOG.md | 3 ++ Sources/AgentsCore/OwnedDuplexProcess.swift | 41 +++++++++++-------- .../PackageLifecycleTests.swift | 35 ++++++++++++++++ 3 files changed, 61 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46cfefd..b0482e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ publication follows the [release checklist](Documentation/Reference/Release.md). - Swift packages can depend on Core by semantic version. Core uses the published MCP Swift SDK 0.12.1 release. +- Cancelled lifecycle commands have time to finish their termination handlers. + Subprocess cleanup reports success when the owned process group has stopped + and its leader has been reaped within the cleanup deadline. ## 0.3.0 diff --git a/Sources/AgentsCore/OwnedDuplexProcess.swift b/Sources/AgentsCore/OwnedDuplexProcess.swift index 9156ebd..d01a63a 100644 --- a/Sources/AgentsCore/OwnedDuplexProcess.swift +++ b/Sources/AgentsCore/OwnedDuplexProcess.swift @@ -166,15 +166,15 @@ package final class OwnedDuplexProcess: @unchecked Sendable { } } - private func signalGroup(_ signal: Int32) -> Bool { + private func signalGroup(_ signal: Int32) { lock.withLock { - guard owned && !reaped else { return false } + guard owned && !reaped else { return } var exited = false guard platform_duplex_observe(identifier, &exited) == 0 else { owned = false - return false + return } - return platform_duplex_signal(identifier, signal) == 0 + _ = platform_duplex_signal(identifier, signal) } } @@ -224,20 +224,25 @@ package final class OwnedDuplexProcess: @unchecked Sendable { /// members remain or the cleanup deadline fails. False means the /// kernel did not confirm cleanup; callers must not report complete success. package func finish(grace: Duration, terminate: Duration, killWait: Duration) async -> Bool { - closeInput() - try? await Task.sleep(for: grace) - let term = signalGroup(SIGTERM) - try? await Task.sleep(for: terminate) - let killed = signalGroup(SIGKILL) - closeOutput() - let deadline = ContinuousClock.now + killWait - repeat { - if reapIfExited() { return ContinuousClock.now <= deadline && term && killed } - try? await Task.sleep(for: .milliseconds(2)) - } while ContinuousClock.now < deadline - // No further group signals follow release of the reserved identity. - _ = reapIfExited(requireQuiescence: false) - return false + // Keep the cleanup waits independent of caller cancellation. + let cleanup = Task { + closeInput() + try? await Task.sleep(for: grace) + signalGroup(SIGTERM) + try? await Task.sleep(for: terminate) + signalGroup(SIGKILL) + closeOutput() + let deadline = ContinuousClock.now + killWait + repeat { + // Quiescence and reap confirm cleanup even if a signal attempt failed. + if reapIfExited() { return ContinuousClock.now <= deadline } + try? await Task.sleep(for: .milliseconds(2)) + } while ContinuousClock.now < deadline + // No further group signals follow release of the reserved identity. + _ = reapIfExited(requireQuiescence: false) + return false + } + return await cleanup.value } deinit { diff --git a/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift b/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift index 4d6e5ce..513a7f6 100644 --- a/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift +++ b/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift @@ -605,6 +605,41 @@ struct PackageLifecycleTests { } } + @Test func cancelledCommandHasTimeToFinishItsTermHandler() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + lifecycle: + pre-install: + - type: command + timeout: 10 + run: | + trap '/bin/sleep 0.03; exit 42' TERM + printf '%s' "$$" > count.tmp + /bin/mv count.tmp count + /bin/sleep 15 & wait "$!" + """) + _ = try await fixture.enable() + let review = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) + let task = Task { await LifecycleOperations.executeTest(review) } + defer { task.cancel() } + let deadline = ContinuousClock.now + .seconds(5) + while !fixture.exists(fixture.counter), ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(5)) + } + task.cancel() + let results = try fixture.completed(await task.value) + let pid = try #require(Int32(fixture.counterText())) + let result = try #require(results.first) + #expect(result.disposition == .commandCancelled) + #expect(result.exitStatus == 42) + #expect(result.processGroupCleanedUp == true) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + } + } + @Test func staleApplyReportsPreStartsAndSuppressesPost() async throws { let fixture = try LifecycleFixture() try await fixture.withoutAdministratorFiles { From d623a4a6e942c2e2c66e983ad5b97be8f6d3bbe4 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:52:58 +0800 Subject: [PATCH 3/5] test: verify lifecycle cancellation waits before kill --- .../AgentsUpdatesTests/PackageLifecycleTests.swift | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift b/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift index 513a7f6..3163657 100644 --- a/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift +++ b/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift @@ -605,7 +605,7 @@ struct PackageLifecycleTests { } } - @Test func cancelledCommandHasTimeToFinishItsTermHandler() async throws { + @Test func cancelledCommandWaitsForTerminationGraceBeforeKill() async throws { let fixture = try LifecycleFixture() try await fixture.withoutAdministratorFiles { try fixture.write( @@ -616,10 +616,10 @@ struct PackageLifecycleTests { - type: command timeout: 10 run: | - trap '/bin/sleep 0.03; exit 42' TERM + trap '' TERM printf '%s' "$$" > count.tmp /bin/mv count.tmp count - /bin/sleep 15 & wait "$!" + exec /bin/sleep 15 """) _ = try await fixture.enable() let review = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) @@ -629,12 +629,16 @@ struct PackageLifecycleTests { while !fixture.exists(fixture.counter), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(5)) } + let cancelledAt = ContinuousClock.now task.cancel() - let results = try fixture.completed(await task.value) + let submission = await task.value + let cleanupTime = cancelledAt.duration(to: .now) + let results = try fixture.completed(submission) let pid = try #require(Int32(fixture.counterText())) let result = try #require(results.first) #expect(result.disposition == .commandCancelled) - #expect(result.exitStatus == 42) + #expect(result.signal == SIGKILL) + #expect(cleanupTime >= .milliseconds(100)) #expect(result.processGroupCleanedUp == true) #expect(kill(pid, 0) == -1 && errno == ESRCH) } From 5de4d60fcbfa65a2c3b85c5c4642b335eea898ed Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:34:17 +0800 Subject: [PATCH 4/5] chore: resolve the Core project declaration --- .agent/agents.resolved | 48 +----------------------------------------- 1 file changed, 1 insertion(+), 47 deletions(-) diff --git a/.agent/agents.resolved b/.agent/agents.resolved index 24e08d3..bbd005a 100644 --- a/.agent/agents.resolved +++ b/.agent/agents.resolved @@ -1,47 +1 @@ -{ - "instructions": { - "chatgpt": {}, - "sections": [ - { - "hash": "sha256:b954b104c6cf0639214a105a846d4fc8e73fd55f14eb695f407f942b905bf22e", - "name": "guide", - "path": ".agent/instructions/guide.md", - "source": "." - }, - { - "hash": "sha256:a45b15d662eecec4b252fa2e35a608bab0ee137fae525669097f45d0f8c3f39d", - "name": "shared/swift-package-route", - "path": ".agent/instructions/shared/swift-package-route.md", - "revision": "fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea", - "source": "github.com/agents-tools/.github" - }, - { - "hash": "sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825", - "name": "shared/swift-package-tests", - "path": ".agent/instructions/shared/swift-package-tests.md", - "revision": "fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea", - "source": "github.com/agents-tools/.github" - } - ], - "targets": { - "AGENTS.md": { - "agents": ["claude-code", "codex"], - "blockHash": "sha256:a025a4ce7d403ace72e30ffe5b2922f571c44f0f6ea52998f5a1bfe6a7ee3fd6", - "created": false, - "headingOffset": 0 - } - } - }, - "skills": {}, - "sources": { - "github.com/agents-tools/.github": { - "kind": "git", - "path": ".agent", - "requirement": { - "branch": "master" - }, - "url": "https://github.com/agents-tools/.github" - } - }, - "version": 1 -} +{"components":{"sha256:3c1ea5baf10fa99ee7576e64c3256b78f4bd9aeb99441b32f6431dfa0e129274":{"chatGPT":false,"conditions":[{}],"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","kind":"instructions","name":"guide","payload":{"kind":"object","object":{"name":{"kind":"string","text":"guide"},"native":{"kind":"object","object":{}},"sourceHash":{"kind":"string","text":"sha256:b954b104c6cf0639214a105a846d4fc8e73fd55f14eb695f407f942b905bf22e"}}},"recipients":["claude-code","codex"],"resources":["sha256:5011da2b72050c86a0f02bcfc069913fa95d30f5b20bf44a55496494424caa97"],"root":".","source":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8"},"sha256:754407554f06d2e1ae23a32c4e2bc39d16781cf468fed1a48e35def4f0836426":{"chatGPT":false,"conditions":[{}],"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","kind":"instructions","name":"shared/swift-package-route","payload":{"kind":"object","object":{"name":{"kind":"string","text":"shared/swift-package-route"},"native":{"kind":"object","object":{}},"sourceHash":{"kind":"string","text":"sha256:a45b15d662eecec4b252fa2e35a608bab0ee137fae525669097f45d0f8c3f39d"}}},"recipients":["claude-code","codex"],"resources":["sha256:cb6aea4e7350afe57cdb7729e9b9daabf33eae2286d59f5314a0ae605f29c9f3"],"revision":"fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea","root":".","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"},"sha256:e4a73605a9830d1c8804aebf5558b8c0c2af26fa405ce5b6591d91c943db5d16":{"chatGPT":false,"conditions":[{}],"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","kind":"instructions","name":"shared/swift-package-tests","payload":{"kind":"object","object":{"name":{"kind":"string","text":"shared/swift-package-tests"},"native":{"kind":"object","object":{}},"sourceHash":{"kind":"string","text":"sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825"}}},"recipients":["claude-code","codex"],"resources":["sha256:3e6e83f98fceb7ee2f89a4e7e6eac3a396d02b1c8341f6ec516e1f230e2c2a11"],"revision":"fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea","root":".","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"}},"contentObjects":{"sha256:b954b104c6cf0639214a105a846d4fc8e73fd55f14eb695f407f942b905bf22e":"LS0tCmRlc2NyaXB0aW9uOiBLZWVwIGFnZW50cy10b29scy9jb3JlJ3MgbW9kdWxlcywgZGVwZW5kZW5jeSBkaXJlY3Rpb24gYW5kIHB1YmxpYyBzdXJmYWNlIHdpdGhpbiB0aGVpciBib3VuZGFyaWVzLgotLS0KIyBjb3JlIEFnZW50IEd1aWRlCgojIyBUYXNrIFJvdXRlCgotIFJ1biB0aGUgYnVpbGQsIHRlc3QgYW5kIHN0cmljdCBmb3JtYXR0aW5nIGNoZWNrcyBpbiBgUkVBRE1FLm1kI2RldmVsb3BtZW50YAogIGJlZm9yZSBoYW5kb2ZmLgotIEZvciB3b3JrZmxvdyBjaGFuZ2VzLCBydW4gYGFjdGlvbmxpbnRgIG9uIGV2ZXJ5IHdvcmtmbG93LgotIENvbW11bml0eSBmaWxlcyBhbmQgdGVtcGxhdGVzIGFyZSBvcmdhbml6YXRpb24gZGVmYXVsdHMgaW4KICBgYWdlbnRzLXRvb2xzLy5naXRodWJgOyB0aGlzIHJlcG9zaXRvcnkga2VlcHMgYENPREVPV05FUlNgLCB0aGUgRGVwZW5kYWJvdAogIGNvbmZpZ3VyYXRpb24gYW5kIHdvcmtmbG93IGNhbGxlcnMgdW5kZXIgYC5naXRodWIvYC4KCiMjIE1vZHVsZSBCb3VuZGFyaWVzCgotIEtlZXAgZWFjaCB0YXJnZXQncyByZXNwb25zaWJpbGl0aWVzLCBkZXBlbmRlbmNpZXMgYW5kIGFjY2VzcyBsZXZlbHMgYXMKICBgRG9jdW1lbnRhdGlvbi9BcmNoaXRlY3R1cmUvUGFja2FnZS5tZGAgc3RhdGVzLCBhbmQgdXBkYXRlIGl0IHdpdGggdGhlCiAgZGVwZW5kZW5jeSBncmFwaCBpbiBgUGFja2FnZS5zd2lmdGAuCi0gS2VlcCBwYWNrYWdlLWRvbWFpbiBwcmVmaXhlcyBvdXQgb2YgaW50ZXJuYWwgdGFyZ2V0IG5hbWVzIHVubGVzcyB0aGUgcGFja2FnZQogIGJvdW5kYXJ5IHN0b3BzIG1ha2luZyB0aGF0IGNvbnRleHQgY2xlYXIuCi0gRGlzYWJsZSBhdXRvbWF0aWMgbWFpbnRlbmFuY2UgYW5kIGdjIGluIGZpeHR1cmUgR2l0IHJlcG9zaXRvcmllcy4K"},"deployments":[{"created":false,"expectedHash":"sha256:a025a4ce7d403ace72e30ffe5b2922f571c44f0f6ea52998f5a1bfe6a7ee3fd6","headingOffset":0,"id":"instructions:AGENTS.md","owners":["sha256:3c1ea5baf10fa99ee7576e64c3256b78f4bd9aeb99441b32f6431dfa0e129274","sha256:754407554f06d2e1ae23a32c4e2bc39d16781cf468fed1a48e35def4f0836426","sha256:e4a73605a9830d1c8804aebf5558b8c0c2af26fa405ce5b6591d91c943db5d16"],"ownership":"generated","recipients":["claude-code","codex"],"route":"agents/instructions@1","target":{"kind":"registered","path":"AGENTS.md","root":"project"}}],"groups":[],"lowerings":[{"artifacts":[{"hash":"sha256:a025a4ce7d403ace72e30ffe5b2922f571c44f0f6ea52998f5a1bfe6a7ee3fd6","kind":"file","name":"instructions:AGENTS.md"}],"deployments":["instructions:AGENTS.md"],"format":"agents/instructions@1","id":"instructions:AGENTS.md","inputs":["sha256:3c1ea5baf10fa99ee7576e64c3256b78f4bd9aeb99441b32f6431dfa0e129274","sha256:754407554f06d2e1ae23a32c4e2bc39d16781cf468fed1a48e35def4f0836426","sha256:e4a73605a9830d1c8804aebf5558b8c0c2af26fa405ce5b6591d91c943db5d16"],"layout":{"kind":"object","object":{"headingOffset":{"integer":0,"kind":"integer"},"name":{"kind":"string","text":"instructions:AGENTS.md"}}},"platform":"macos","resources":["sha256:5011da2b72050c86a0f02bcfc069913fa95d30f5b20bf44a55496494424caa97","sha256:cb6aea4e7350afe57cdb7729e9b9daabf33eae2286d59f5314a0ae605f29c9f3","sha256:3e6e83f98fceb7ee2f89a4e7e6eac3a396d02b1c8341f6ec516e1f230e2c2a11"]}],"occurrences":[{"component":"sha256:3c1ea5baf10fa99ee7576e64c3256b78f4bd9aeb99441b32f6431dfa0e129274","condition":{},"consumerEditable":true,"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","dependencies":["sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8"],"id":0,"manifestPath":".agent/agents.yaml","recipients":["claude-code","codex"]},{"component":"sha256:754407554f06d2e1ae23a32c4e2bc39d16781cf468fed1a48e35def4f0836426","condition":{},"consumerEditable":true,"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","dependencies":["sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"],"id":1,"manifestPath":".agent/agents.yaml","recipients":["claude-code","codex"]},{"component":"sha256:e4a73605a9830d1c8804aebf5558b8c0c2af26fa405ce5b6591d91c943db5d16","condition":{},"consumerEditable":true,"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","dependencies":["sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"],"id":2,"manifestPath":".agent/agents.yaml","recipients":["claude-code","codex"]}],"resources":{"sha256:3e6e83f98fceb7ee2f89a4e7e6eac3a396d02b1c8341f6ec516e1f230e2c2a11":{"entries":[{"byteCount":421,"executable":false,"kind":"file","path":"."}],"hash":"sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825","kind":"git","path":".agent/instructions/shared/swift-package-tests.md","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6","support":[]},"sha256:5011da2b72050c86a0f02bcfc069913fa95d30f5b20bf44a55496494424caa97":{"entries":[{"byteCount":903,"executable":false,"kind":"file","object":"sha256:b954b104c6cf0639214a105a846d4fc8e73fd55f14eb695f407f942b905bf22e","path":"."}],"hash":"sha256:b954b104c6cf0639214a105a846d4fc8e73fd55f14eb695f407f942b905bf22e","kind":"embedded","path":".agent/instructions/guide.md","source":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","support":[]},"sha256:cb6aea4e7350afe57cdb7729e9b9daabf33eae2286d59f5314a0ae605f29c9f3":{"entries":[{"byteCount":1077,"executable":false,"kind":"file","path":"."}],"hash":"sha256:a45b15d662eecec4b252fa2e35a608bab0ee137fae525669097f45d0f8c3f39d","kind":"git","path":".agent/instructions/shared/swift-package-route.md","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6","support":[]}},"sourceUses":[{"requirement":{"branch":"master"},"root":".agent","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"}],"sources":{"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6":{"kind":"git","revision":"fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea","transport":"https://github.com/agents-tools/.github"},"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8":{"kind":"local","location":{"kind":"registered","path":".","root":"project"},"revision":"live"}},"version":2} From a2b665cbd4ad07aa8df0e191742f53855d699940 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:54:32 +0800 Subject: [PATCH 5/5] fix!: remove the global configuration importer --- CHANGELOG.md | 7 + Sources/AgentsCore/FileTransaction.swift | 28 +- Sources/AgentsCore/LedgerStateStore.swift | 2 +- .../AgentsCore/NativeTargetCoordination.swift | 4 +- Sources/AgentsCore/ResolvedState.swift | 25 - Sources/AgentsCore/SourceRequirement.swift | 2 +- Sources/AgentsCore/StateInspection.swift | 17 - Sources/AgentsCore/StateStore.swift | 53 +- Sources/AgentsCore/TransactionPaths.swift | 7 +- Sources/AgentsSkills/SkillOperations.swift | 10 - .../Bundles/AuthorLockedMembers.swift | 2 +- .../ExistingGlobalConfiguration.swift | 336 --------- .../ExistingGlobalConfigurationJSON.swift | 159 ---- .../ImportedConfigurationLedger.swift | 460 ------------ Sources/AgentsUpdates/ScopeInspection.swift | 1 - .../MappingReadLocationsTests.swift | 4 +- .../ExistingGlobalConfigurationTests.swift | 688 ------------------ Tests/StateTestProcess/main.swift | 3 - 18 files changed, 23 insertions(+), 1785 deletions(-) delete mode 100644 Sources/AgentsUpdates/ExistingGlobalConfiguration.swift delete mode 100644 Sources/AgentsUpdates/ExistingGlobalConfigurationJSON.swift delete mode 100644 Sources/AgentsUpdates/ImportedConfigurationLedger.swift delete mode 100644 Tests/AgentsUpdatesTests/ExistingGlobalConfigurationTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index b0482e6..3935eb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,13 @@ publication follows the [release checklist](Documentation/Reference/Release.md). Subprocess cleanup reports success when the owned process group has stopped and its leader has been reaped within the cleanup deadline. +### Removed + +- Removed `ExistingGlobalConfiguration`, which converted user `agents.json` + declarations and version 1 locks. Finish any pending conversion with the + version that started it before upgrading. Declare user configuration in + `~/.agents/agents.yaml` and use the standard preview and apply flow. + ## 0.3.0 ### Added diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 3b65da6..fab0cf5 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -497,26 +497,6 @@ package final class FileTransaction { throw CoreError.invalidState("transaction recovery is required") } try queueReceipt() - let paths = Set(requests.map(\.path)) - let originalLedger = "state/" + StateStore.originalLedgerFileName - let importingConfiguration = paths.contains(originalLedger) - if importingConfiguration { - guard - paths == [ - originalLedger, "state/" + StateStore.declarationFileName, - "state/" + StateStore.resolvedFileName, - ], requests.count == 3, requests.allSatisfy(\.installs), - requests.first(where: { $0.path == originalLedger })?.evidence.exists == false, - requests.first(where: { $0.path == "state/" + StateStore.declarationFileName })? - .evidence.exists == false, - requests.first(where: { $0.path == "state/" + StateStore.resolvedFileName })? - .evidence.exists == true - else { - throw CoreError.invalidState( - "configuration import requires the declaration, resolved ledger, and original ledger copy" - ) - } - } for state in receiptStates.values { try state.evidence.validate() } try validateUnchanged() for request in requests { try request.evidence.validate() } @@ -530,11 +510,9 @@ package final class FileTransaction { try session.createContainers() try session.checkCapabilities() // Capability probing may only touch missing ancestry, journal and private containers. - if !importingConfiguration, - session.journal.entries.contains(where: { - ["state/agents.watch", "state/agents.resolved"].contains($0.path) - }) - { + if session.journal.entries.contains(where: { + ["state/agents.watch", "state/agents.resolved"].contains($0.path) + }) { try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() } for (index, request) in requests.enumerated() { diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift index 1cc14d8..fe3cbc1 100644 --- a/Sources/AgentsCore/LedgerStateStore.swift +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -105,7 +105,7 @@ extension StateStore { }, expecting: prepared.evidence(for: resolvedURL)) } - private func ledgerBytes(limits: LedgerLimits) throws -> Data? { + package func ledgerBytes(limits: LedgerLimits) throws -> Data? { guard let directory = try openDirectoryIfPresent(), try directory.info(Self.resolvedFileName) != nil else { return nil } diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index c195ee0..7ccb025 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -1163,7 +1163,7 @@ extension StateStore { routes: Set, installations: [SkillInstallationTarget] = [], writable: Bool, checkpoint: (String) throws -> Void = { _ in }, existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil, - onReadLocation: ((URL) -> Void)? = nil, admitRecovery: Bool = true, + onReadLocation: ((URL) -> Void)? = nil, _ body: () throws -> T ) throws -> T { func recordAncestry(_ url: URL) { @@ -1198,7 +1198,7 @@ extension StateStore { } for route in routes where !route.shared && route.isNamed { _ = try nativeTarget(for: route) } while true { - let before = try admitRecovery ? pendingCoordinationJournal(diagnosing: !writable) : nil + let before = try pendingCoordinationJournal(diagnosing: !writable) var resources: [SharedResource] = [] var createdAncestry: [(URL, DirectoryAccessEvidence)] = [] if writable { diff --git a/Sources/AgentsCore/ResolvedState.swift b/Sources/AgentsCore/ResolvedState.swift index 7de8947..976c359 100644 --- a/Sources/AgentsCore/ResolvedState.swift +++ b/Sources/AgentsCore/ResolvedState.swift @@ -302,31 +302,6 @@ public struct ResolvedState: Codable, Equatable, Sendable { else { throw CoreError.invalidState("Git item needs an exact revision and path") } } } - - package var normalized: ResolvedState { - var result = self - for id in result.sources.keys { - let requirement = result.sources[id]?.requirement?.canonical - result.sources[id]?.requirement = requirement - } - for name in result.skills.keys { - result.skills[name]?.artifact?.files?.sort { $0.path < $1.path } - } - for index in result.instructions.sections.indices { - result.instructions.sections[index].artifact?.files?.sort { $0.path < $1.path } - } - for name in result.instructions.chatgpt.keys { - guard var prompt = result.instructions.chatgpt[name] else { continue } - for index in prompt.sections.indices { - prompt.sections[index].artifact?.files?.sort { $0.path < $1.path } - } - result.instructions.chatgpt[name] = prompt - } - for path in result.instructions.targets.keys { - result.instructions.targets[path]?.agents.sort { $0.rawValue < $1.rawValue } - } - return result - } } package enum StateValidation { diff --git a/Sources/AgentsCore/SourceRequirement.swift b/Sources/AgentsCore/SourceRequirement.swift index 23e7995..74728d2 100644 --- a/Sources/AgentsCore/SourceRequirement.swift +++ b/Sources/AgentsCore/SourceRequirement.swift @@ -44,7 +44,7 @@ public enum SourceRequirement: Codable, Equatable, Sendable { self = requirement } - package static func decodeIfPresent(from decoder: Decoder) throws -> SourceRequirement? { + private static func decodeIfPresent(from decoder: Decoder) throws -> SourceRequirement? { let container = try decoder.container(keyedBy: CodingKeys.self) let keys: [CodingKeys] = [.branch, .revision, .exact, .from, .upToNextMinor] let present = keys.filter { container.contains($0) } diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index f589c2d..795a013 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -9,21 +9,6 @@ extension StateStore { try context.requireHeldScope() } - package var configurationJSONURL: URL? { - scope == .user ? directory.appendingPathComponent(Self.configurationJSONFileName) : nil - } - - package func stateEntryExists(_ name: String) throws -> Bool { - try openDirectoryIfPresent()?.info(name) != nil - } - - package func configurationInputBytes(_ name: String) throws -> Data? { - guard let directory = try openDirectoryIfPresent(), - try directory.info(name) != nil - else { return nil } - return try directory.read(name, maximumBytes: LedgerLimits.standard.encodedBytes) - } - /// Metadata and admission entries, including absent paths. Only the supplied scope root /// resolves through links; state-directory and lock links do not grant new path authority. package var metadataReadLocations: [URL] { @@ -38,8 +23,6 @@ extension StateStore { TransactionJournal.fileName, TransactionJournal.incompleteFileName, "watch-refs.pending", ].map { directory.appendingPathComponent($0) } - + (scope == .user - ? [directory.appendingPathComponent(Self.configurationJSONFileName)] : []) } } diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index 6980909..dc9444b 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -23,8 +23,6 @@ public struct StateStore: Sendable { package static let declarationFileName = "agents.yaml" package static let resolvedFileName = "agents.resolved" package static let watchFileName = "agents.watch" - package static let configurationJSONFileName = "agents.json" - package static let originalLedgerFileName = "agents.resolved.original" /// The scope files a state transaction may replace. package static let marketplaceDirectoryFileName = "marketplaces.yaml" package static let sourcePolicyFileName = "source-policy.yaml" @@ -102,34 +100,9 @@ public struct StateStore: Sendable { } } - /// Imports configuration under the scope writer lock. The import validates its own state - /// files and preserves the existing cache references. - package func withConfigurationImportLock( - checkpoint: @escaping (String) throws -> Void, beforeCreatingLock: () throws -> Void, - _ body: () throws -> T - ) throws -> T { - guard scope == .user, try openDirectoryIfPresent() != nil else { - throw CoreError.invalidState( - "the global configuration directory is missing: \(directory.path)") - } - return try withCoordination( - routes: [], writable: true, checkpoint: checkpoint, admitRecovery: false - ) { - if let directory = try openDirectoryIfPresent(), - try directory.info(".agents.lock") == nil, - try !TransactionJournal.isPresent(in: directory), - try directory.info("watch-refs.pending") == nil - { - try beforeCreatingLock() - } - return try withScopeLock( - createIfMissing: false, checkpoint: checkpoint, importingConfiguration: true, body) - } - } - private func withScopeLock( createIfMissing: Bool = true, checkpoint: @escaping (String) throws -> Void = { _ in }, - outcome: TransactionOutcome? = nil, importingConfiguration: Bool = false, + outcome: TransactionOutcome? = nil, _ body: () throws -> T ) throws -> T { if try openDirectoryIfPresent() == nil, !createIfMissing { @@ -140,11 +113,9 @@ public struct StateStore: Sendable { } // Without a scope lock, journal or ref-cleanup marker, invalid or orphaned state stops the // operation before the scope lock exists. Otherwise recovery precedes these checks. - if !importingConfiguration, - ![".agents.lock", TransactionJournal.fileName, "watch-refs.pending"].contains(where: { - FileManager.default.fileExists(atPath: directory.appendingPathComponent($0).path) - }) - { + if ![".agents.lock", TransactionJournal.fileName, "watch-refs.pending"].contains(where: { + FileManager.default.fileExists(atPath: directory.appendingPathComponent($0).path) + }) { _ = try declarationBytes() _ = try readLedger() _ = try readWatch() @@ -180,22 +151,6 @@ public struct StateStore: Sendable { throw CoreError.invalidState("missing scope lock admission") } try context.bindScope(scopeDirectory, descriptor: descriptor) - if importingConfiguration { - // Confirmation owns only the import journal. A scope operation may have started - // after preview, so inspect its pending markers under the writer lock. - guard try !TransactionJournal.isPresent(in: scopeDirectory), - try scopeDirectory.info("watch-refs.pending") == nil - else { - throw CoreError.recoveryPending( - "A configuration operation is pending at \(directory.path). " - + "Finish it in the tool that started it, then preview again." - ) - } - try verifyCoordinationAdmission() - let result = try body() - try context.validateScope() - return result - } try verifyCoordinationAdmission() let recovered = try FileTransaction.recover( store: self, outcome: outcome, checkpoint: checkpoint) diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 7d6b947..2b7b049 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -262,8 +262,7 @@ struct TransactionPaths { descendants.count == 1 && (StateStore.stateFileNames.contains(descendants[0]) || descendants[0] == StateStore.sourcePolicyFileName - || descendants[0] == StateStore.marketplaceDirectoryFileName - || (store.scope == .user && descendants[0] == StateStore.originalLedgerFileName)) + || descendants[0] == StateStore.marketplaceDirectoryFileName) let cache = descendants.first == "cache" && descendants.count >= 3 && ((descendants[1] == "materialized" && (3...4).contains(descendants.count)) @@ -352,7 +351,7 @@ package struct SkillInstallationTarget: Sendable { let parentIdentity: FileObjectIdentity? /// Coalesces identical parent checks without sharing a successful check across phases. - package static func distinctAuthorities(_ targets: [Self]) -> [Self] { + static func distinctAuthorities(_ targets: [Self]) -> [Self] { struct Key: Hashable { let loader: Data let descendants: [Data] @@ -371,7 +370,7 @@ package struct SkillInstallationTarget: Sendable { } } - package func validateAuthority() throws { + func validateAuthority() throws { let parent = try authority.physicalDirectory() guard parent.path.utf8.elementsEqual(url.deletingLastPathComponent().path.utf8), try parentIdentity.map({ try DirectoryHandle(at: parent).objectIdentity == $0 }) ?? true diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 82eaeb2..33885e9 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -213,16 +213,6 @@ public enum SkillOperations { } extension SkillOperations { - package static func lockedMetadata(at directory: URL, installedName: String) throws -> Skill { - let metadata = try Discovery.parseSkill( - at: directory.appendingPathComponent("SKILL.md"), includeInternal: true) - guard let metadata, PathSafety.sanitizeName(metadata.name) == installedName else { - throw CoreError.invalidSkill( - "SKILL.md no longer identifies the locked skill \(installedName)") - } - return metadata - } - package static func inspect( _ options: AddOptions, declaration: Declaration ) throws -> (SourceDeclaration, String, [Skill]) { diff --git a/Sources/AgentsUpdates/Bundles/AuthorLockedMembers.swift b/Sources/AgentsUpdates/Bundles/AuthorLockedMembers.swift index c2f9204..a4d0c19 100644 --- a/Sources/AgentsUpdates/Bundles/AuthorLockedMembers.swift +++ b/Sources/AgentsUpdates/Bundles/AuthorLockedMembers.swift @@ -7,7 +7,7 @@ extension AuthorCapture { mutating func addLocked( _ selection: [MarketplaceMemberKey], store: StateStore, policy: AuthorPackagePolicy ) throws { - guard let bytes = try store.configurationInputBytes(StateStore.resolvedFileName) else { + guard let bytes = try store.ledgerBytes(limits: .standard) else { throw CoreError.notFound("agents.resolved for selected package dependencies") } let ledger = try ResolvedLedgerCodec.decode(bytes, limits: .standard) diff --git a/Sources/AgentsUpdates/ExistingGlobalConfiguration.swift b/Sources/AgentsUpdates/ExistingGlobalConfiguration.swift deleted file mode 100644 index 74641df..0000000 --- a/Sources/AgentsUpdates/ExistingGlobalConfiguration.swift +++ /dev/null @@ -1,336 +0,0 @@ -import AgentsCore -import AgentsManifest -import Components -import Foundation - -/// A read-only preview of the global configuration to apply. -public struct ExistingGlobalConfigurationPreview: Sendable { - /// The number of declared source aliases. - public let sourceCount: Int - /// The number of distinct skills in the saved installation records. - public let skillCount: Int - /// Existing managed skill installations, counting shared physical paths once. - public let installationCount: Int - /// Locked instruction sections, including the sections selected by each named prompt. - public let instructionCount: Int - /// The YAML declaration to be created on confirmation. - public let declarationURL: URL - /// The resolved ledger to write on confirmation. - public let ledgerURL: URL - /// The new file that will contain the exact bytes of the original lock. - public let originalLedgerURL: URL - - fileprivate let store: StateStore - fileprivate let declaration: Data - fileprivate let ledger: Data - fileprivate let originalLedger: Data - fileprivate let evidence: ConfigurationImportEvidence - - fileprivate init( - store: StateStore, declaration: Data, ledger: Data, originalLedger: Data, - sourceCount: Int, skillCount: Int, installationCount: Int, instructionCount: Int, - evidence: ConfigurationImportEvidence - ) { - self.store = store - self.declaration = declaration - self.ledger = ledger - self.originalLedger = originalLedger - self.sourceCount = sourceCount - self.skillCount = skillCount - self.installationCount = installationCount - self.instructionCount = instructionCount - self.evidence = evidence - declarationURL = store.declarationURL - ledgerURL = store.resolvedURL - originalLedgerURL = store.directory.appendingPathComponent(StateStore.originalLedgerFileName) - } -} - -public enum ExistingGlobalConfigurationError: LocalizedError, Equatable, Sendable { - case unavailable - case stalePreview(String) - case conflict(String) - case recovery(String) - - public var errorDescription: String? { - switch self { - case .unavailable: - "Use Existing Configuration requires agents.json and its associated agents.resolved in a scope without agents.yaml." - case .stalePreview(let detail): - "The global configuration changed after the preview. Preview it again. \(detail)" - case .conflict(let detail): - "There is a conflict in the existing global configuration. \(detail)" - case .recovery(let detail): - detail - } - } -} - -public enum ExistingGlobalConfiguration { - /// Checks whether a global configuration is available to import using its state files. - public static func isAvailable(environment: RuntimeEnvironment) throws -> Bool { - let store = StateStore(scope: .user, environment: environment) - return try withImportErrors { - try store.withReadLock(onPendingRecovery: { throw pendingOperation(in: store) }) { - try importableLedger(in: store) != nil - } - } - } - - public static func preview(environment: RuntimeEnvironment) throws - -> ExistingGlobalConfigurationPreview - { - let store = StateStore(scope: .user, environment: environment) - return try withImportErrors { - try store.withReadLock(onPendingRecovery: { throw pendingOperation(in: store) }) { - guard let bytes = try importableLedger(in: store) else { - throw ExistingGlobalConfigurationError.unavailable - } - let files = try configurationInputs(in: store) - guard files.yaml.bytes == nil, files.ledger.bytes == bytes, - let json = files.configurationJSON.bytes - else { - throw ExistingGlobalConfigurationError.stalePreview( - "The configuration files changed during inspection.") - } - guard files.originalLedger.bytes == nil else { - throw ExistingGlobalConfigurationError.conflict( - "A saved ledger copy already exists at \(files.originalLedger.evidence.url.path). " - + "Move that copy to a safe location before previewing again.") - } - try LedgerAdmission.check(json, limits: .standard) - let declaration = try StateStore.decode(json, as: ExistingGlobalConfigurationJSON.self) - .declaration(environment: environment) - let saved = try StateStore.decode(bytes, as: ResolvedState.self) - try saved.validate() - _ = try store.readWatch() - let yaml = - try DeclarationEditPlan.bytes( - replacing: Declaration(), with: declaration, in: nil, - identity: DocumentIdentity(store.declarationURL.path), environment: environment) - ?? Array("version: 1\n".utf8) - var conversion = ImportedConfigurationLedger( - store: store, declaration: declaration, saved: saved) - let candidate = try conversion.convert() - let encoded = try ResolvedLedgerCodec.encode(candidate, limits: .standard) - let evidence = ConfigurationImportEvidence( - yaml: files.yaml.evidence, ledger: files.ledger.evidence, - originalLedger: files.originalLedger.evidence, - untouched: [files.configurationJSON.evidence, files.watch.evidence] - + conversion.evidence.values.sorted { $0.url.path < $1.url.path }, - installationAuthorities: SkillInstallationTarget.distinctAuthorities( - conversion.installations), - editSources: conversion.editSources.values.sorted { - $0.directory.path < $1.directory.path - }, - offlinePins: conversion.offlinePins, store: store) - try evidence.validate(excludingTargets: []) - return ExistingGlobalConfigurationPreview( - store: store, declaration: Data(yaml), ledger: encoded, originalLedger: bytes, - sourceCount: declaration.sourceDeclarations.count, skillCount: saved.skills.count, - installationCount: conversion.installed.count, - instructionCount: saved.instructions.sections.count - + saved.instructions.chatgpt.values.reduce(0) { $0 + $1.sections.count }, - evidence: evidence) - } - } - } - - /// Publishes only the captured state files. Preview a changed scope again before confirming. - public static func apply(_ preview: ExistingGlobalConfigurationPreview) throws { - try apply(preview, checkpoint: { _ in }) - } - - package static func apply( - _ preview: ExistingGlobalConfigurationPreview, checkpoint: @escaping (String) throws -> Void - ) throws { - try withImportErrors { - let store = preview.store - let outcome = TransactionOutcome() - try store.withConfigurationImportLock( - checkpoint: checkpoint, - beforeCreatingLock: { try preview.evidence.validateFiles() } - ) { - try preview.evidence.validate(excludingTargets: []) - let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) - transaction.requireUnchanged(since: preview.evidence) - try transaction.replace( - preview.originalLedgerURL, with: .data(preview.originalLedger), - expecting: preview.evidence.originalLedger) - try transaction.replace( - preview.declarationURL, with: .data(preview.declaration), - expecting: preview.evidence.yaml) - try transaction.replace( - preview.ledgerURL, with: .data(preview.ledger), - expecting: preview.evidence.ledger) - do { - try transaction.commit() - } catch { - if outcome.recoveryPending { - throw ExistingGlobalConfigurationError.recovery( - FileTransaction.recoveryDiagnostic(store: store).message) - } - if outcome.terminal != .committed { throw error } - } - } - } - } - - private static func importableLedger(in store: StateStore) throws -> Data? { - struct Version: Decodable { let version: Int } - guard try !store.stateEntryExists(StateStore.declarationFileName), - try store.stateEntryExists(StateStore.configurationJSONFileName), - let ledger = try store.configurationInputBytes(StateStore.resolvedFileName) - else { return nil } - try LedgerAdmission.check(ledger, limits: .standard) - return try JSONDecoder().decode(Version.self, from: ledger).version == 1 ? ledger : nil - } - - private static func pendingOperation(in store: StateStore) -> ExistingGlobalConfigurationError { - .recovery( - "A configuration operation is pending at \(store.directory.path). " - + "Finish it in the tool that started it, then preview again.") - } - - private typealias StateInput = (bytes: Data?, evidence: TargetPrecondition) - - private static func configurationInputs(in store: StateStore) throws -> ( - configurationJSON: StateInput, yaml: StateInput, ledger: StateInput, originalLedger: StateInput, - watch: StateInput - ) { - try ( - TargetPrecondition.readingFile( - store.directory.appendingPathComponent(StateStore.configurationJSONFileName)), - TargetPrecondition.readingFile(store.declarationURL), - TargetPrecondition.readingFile(store.resolvedURL), - TargetPrecondition.readingFile( - store.directory.appendingPathComponent(StateStore.originalLedgerFileName)), - TargetPrecondition.readingFile(store.watchURL) - ) - } - - private static func withImportErrors(_ operation: () throws -> T) throws -> T { - do { - return try operation() - } catch let error as ExistingGlobalConfigurationError { - throw error - } catch let error as CoreError { - switch error { - case .recoveryPending(let detail): - throw ExistingGlobalConfigurationError.recovery(detail) - case .transactionRecovered: - throw ExistingGlobalConfigurationError.recovery(error.description) - default: - throw ExistingGlobalConfigurationError.conflict(error.description) - } - } catch is CancellationError { - throw CancellationError() - } catch { - throw ExistingGlobalConfigurationError.conflict(String(describing: error)) - } - } -} - -struct ConfigurationImportEvidence: PreparedEvidence, Sendable { - let yaml: TargetPrecondition - let ledger: TargetPrecondition - let originalLedger: TargetPrecondition - let untouched: [TargetPrecondition] - let installationAuthorities: [SkillInstallationTarget] - let editSources: [EditSourceEvidence] - let offlinePins: [OfflinePin] - let store: StateStore - - func validateFiles(excludingTargets targets: Set = []) throws { - for installation in installationAuthorities { - do { try installation.validateAuthority() } catch { - throw ExistingGlobalConfigurationError.stalePreview(installation.url.path) - } - } - for file in [yaml, ledger, originalLedger] + untouched where !targets.contains(file.url.path) { - do { try file.validate() } catch { - throw ExistingGlobalConfigurationError.stalePreview(file.url.path) - } - } - for source in editSources { - do { try source.validate() } catch { - throw ExistingGlobalConfigurationError.stalePreview(source.directory.path) - } - } - } - - func validate(excludingTargets targets: Set) throws { - try validateFiles(excludingTargets: targets) - // Cached resources are covered by file evidence. An exact Git object can disappear - // independently of the scope, even though its content cannot mutate. - for pin in offlinePins { - do { - try SourceCache(store: store).withOfflineSnapshot( - sourceID: pin.identity, source: pin.source, revision: pin.revision - ) { _, _ in () } - } catch { - throw ExistingGlobalConfigurationError.stalePreview( - "Git commit \(pin.revision) for \(pin.identity).") - } - } - } - - struct OfflinePin: Equatable, Sendable { - let identity: String - let source: LockedSource - let revision: String - } -} - -/// A live edit source supplies preview metadata and a content digest. Its directory is -/// read in place. Transaction preimages cover the managed link and the small state files. -struct EditSourceEvidence: Sendable { - let directory: URL - let hash: String - private let authoredURL: URL - private let authoredIdentity: PathIdentity - private let directoryIdentity: PathIdentity - private let linkedMetadata: (url: URL, identity: PathIdentity, hash: String)? - - init(authoredURL: URL, directory: URL, metadata: URL) throws { - self.authoredURL = authoredURL - self.directory = directory - authoredIdentity = try PathIdentity(authoredURL) - directoryIdentity = try PathIdentity(directory) - // The tree digest records a symlink's destination spelling. Metadata parsing also - // depends on the bytes at that destination when SKILL.md is itself a link. - if metadata.path == directory.appendingPathComponent("SKILL.md").path { - linkedMetadata = nil - } else { - linkedMetadata = try (metadata, PathIdentity(metadata), FileHash.sha256Hex(file: metadata)) - } - hash = try "sha256:" + FileHash.folderHash(directory) - try validateIdentity() - } - - func validate() throws { - try validateIdentity() - guard try "sha256:" + FileHash.folderHash(directory) == hash else { - throw ExistingGlobalConfigurationError.stalePreview(directory.path) - } - if let linkedMetadata, try FileHash.sha256Hex(file: linkedMetadata.url) != linkedMetadata.hash { - throw ExistingGlobalConfigurationError.stalePreview(linkedMetadata.url.path) - } - try validateIdentity() - } - - private func validateIdentity() throws { - try authoredIdentity.validate() - try directoryIdentity.validate() - guard authoredURL.resolvingSymlinksInPath() == directory else { - throw ExistingGlobalConfigurationError.stalePreview(authoredURL.path) - } - if let linkedMetadata { - try linkedMetadata.identity.validate() - guard - directory.appendingPathComponent("SKILL.md").resolvingSymlinksInPath() - == linkedMetadata.url - else { throw ExistingGlobalConfigurationError.stalePreview(linkedMetadata.url.path) } - } - } -} diff --git a/Sources/AgentsUpdates/ExistingGlobalConfigurationJSON.swift b/Sources/AgentsUpdates/ExistingGlobalConfigurationJSON.swift deleted file mode 100644 index 37a6272..0000000 --- a/Sources/AgentsUpdates/ExistingGlobalConfigurationJSON.swift +++ /dev/null @@ -1,159 +0,0 @@ -import AgentsCore -import Foundation - -/// The declaration wire format read from agents.json. -struct ExistingGlobalConfigurationJSON: Codable { - let agents: [AgentID]? - let sources: [String: Source]? - let skills: [String: Skill]? - let instructions: InstructionSelection? - let watch: [String]? - - func declaration(environment: RuntimeEnvironment) throws -> Declaration { - let sources = (sources ?? [:]).mapValues { $0.declaration(environment: environment) } - // Installation records name a source by normalized identity, with one discovery root - // per identity in agents.json and agents.resolved. - var aliases: [String: String] = [:] - for alias in sources.keys.sorted() { - let identity = try sources[alias]!.identity(environment: environment) - if let existing = aliases.updateValue(alias, forKey: identity) { - throw CoreError.invalidState( - "Source aliases '\(existing)' and '\(alias)' in agents.json identify the same source. " - + "Use one alias per source and reconcile its selections before previewing again.") - } - } - let declaration = Declaration( - agents: agents, sources: sources, skills: skills?.mapValues(\.declaration), - instructions: instructions?.declaration, watch: watch) - try declaration.validate(environment: environment) - if let instructions = try declaration.instructions { - let sections = - instructions.sectionReferences - + instructions.prompts.flatMap { $0.prompt.sectionReferences } - guard sections.allSatisfy({ $0.source != nil && $0.source != "." }) else { - throw CoreError.invalidState("global instruction selections need a named source") - } - } - return declaration - } - - struct Source: Codable { - private enum CodingKeys: String, CodingKey { - case git, local, path - case wellKnown = "well-known" - } - - let kind: SourceKind - let location: String - let requirement: SourceRequirement? - let path: String? - - init(from decoder: any Decoder) throws { - let fields = try decoder.container(keyedBy: CodingKeys.self) - let kinds: [(CodingKeys, SourceKind)] = [ - (.git, .git), (.local, .local), (.wellKnown, .wellKnown), - ] - let present = kinds.filter { fields.contains($0.0) } - guard present.count == 1, let (key, kind) = present.first else { - throw CoreError.invalidState("a source in agents.json must specify one location") - } - self.kind = kind - location = try fields.decode(String.self, forKey: key) - path = try fields.decodeIfPresent(String.self, forKey: .path) - requirement = try SourceRequirement.decodeIfPresent(from: decoder) - } - - func encode(to encoder: any Encoder) throws { - var fields = encoder.container(keyedBy: CodingKeys.self) - try fields.encode( - location, forKey: kind == .git ? .git : kind == .local ? .local : .wellKnown) - try fields.encodeIfPresent(path, forKey: .path) - try requirement?.encode(to: encoder) - } - - func declaration(environment: RuntimeEnvironment) -> SourceDeclaration { - var source = SourceDeclaration( - kind: kind, location: location, requirement: requirement, path: path) - if kind == .local, !location.hasPrefix("/"), location != "~", !location.hasPrefix("~/") { - source.location = source.localURL(environment: environment).path - } - return source - } - } - - struct Skill: Codable { - let select: Selection - let exclude: [String]? - let agents: [AgentID]? - let mode: InstallMode? - let overrides: [String: Override]? - - private enum CodingKeys: String, CodingKey { case select, exclude, agents, mode, overrides } - private enum UnsupportedKeys: String, CodingKey { case path } - - init(from decoder: any Decoder) throws { - let unsupported = try decoder.container(keyedBy: UnsupportedKeys.self) - if unsupported.contains(.path) { - let alias = decoder.codingPath.last?.stringValue ?? "unknown" - throw CoreError.invalidState( - "skills.\(alias).path is unsupported in agents.json. " - + "Set the discovery path on sources.\(alias).path before previewing again.") - } - let fields = try decoder.container(keyedBy: CodingKeys.self) - select = try fields.decode(Selection.self, forKey: .select) - exclude = try fields.decodeIfPresent([String].self, forKey: .exclude) - agents = try fields.decodeIfPresent([AgentID].self, forKey: .agents) - mode = try fields.decodeIfPresent(InstallMode.self, forKey: .mode) - overrides = try fields.decodeIfPresent([String: Override].self, forKey: .overrides) - } - - var declaration: SkillDeclaration { - .init( - select: select.value, exclude: exclude, agents: agents, mode: mode, - overrides: overrides?.mapValues { .init(agents: $0.agents, mode: $0.mode) }) - } - } - - struct Override: Codable { - let agents: [AgentID]? - let mode: InstallMode? - } - - struct Selection: Codable { - let value: SkillSelection - - init(from decoder: any Decoder) throws { - let field = try decoder.singleValueContainer() - if (try? field.decode(String.self)) == "all" { - value = .all - } else { - value = .names(try field.decode([String].self)) - } - } - - func encode(to encoder: any Encoder) throws { - var field = encoder.singleValueContainer() - switch value { - case .all: try field.encode("all") - case .names(let names): try field.encode(names) - } - } - } - - struct InstructionSelection: Codable { - let agents: [AgentID]? - let sections: [String] - let chatgpt: [String: Prompt]? - - var declaration: InstructionsDeclaration { - .init( - agents: agents, sections: sections, - chatgpt: chatgpt?.mapValues { .init(sections: $0.sections, append: $0.append) }) - } - } - - struct Prompt: Codable { - let sections: [String] - let append: String? - } -} diff --git a/Sources/AgentsUpdates/ImportedConfigurationLedger.swift b/Sources/AgentsUpdates/ImportedConfigurationLedger.swift deleted file mode 100644 index 64e41dc..0000000 --- a/Sources/AgentsUpdates/ImportedConfigurationLedger.swift +++ /dev/null @@ -1,460 +0,0 @@ -import AgentsCore -import AgentsInstructions -import AgentsSkills -import Components -import Foundation - -/// Builds the resolved ledger from saved installation records and independently pinned sources. -struct ImportedConfigurationLedger { - let store: StateStore - let declaration: Declaration - let saved: ResolvedState - var ledger = ResolvedLedger() - var evidence: [URL: TargetPrecondition] = [:] - var installations: [SkillInstallationTarget] = [] - var editSources: [URL: EditSourceEvidence] = [:] - var offlinePins: [ConfigurationImportEvidence.OfflinePin] = [] - var installed = Set() - private var skillTargets: [String: InstallMode] = [:] - private var declaringSource = "" - private var objectBytes = 0 - - private var cache: SourceCache { SourceCache(store: store) } - - init(store: StateStore, declaration: Declaration, saved: ResolvedState) { - self.store = store - self.declaration = declaration - self.saved = saved - } - - mutating func convert() throws -> ResolvedLedger { - let root = LedgerSource( - kind: .local, location: .init(kind: .registered, root: "state", path: "."), revision: "live") - declaringSource = try ResolvedLedgerCodec.digest(root) - ledger.sources[declaringSource] = root - for name in saved.skills.keys.sorted() { - try Task.checkCancellation() - try addSkill(name, locked: saved.skills[name]!) - } - try addInstructions() - if ledger.occurrences.isEmpty { ledger.sources.removeValue(forKey: declaringSource) } - let roots = store.ledgerRoots(recordedIn: ledger) - return try LedgerReplay.withPreparedLowerings( - ledger, store: store, roots: roots, limits: .standard, offline: true - ) { prepared, outputs, _, _ in - let rendered = Dictionary(uniqueKeysWithValues: outputs.map { ($0.name, $0) }) - for deployment in prepared.deployments - where InstructionLocations.isInstructionFormat(deployment.route) { - guard let bytes = rendered[deployment.id]?.bytes, - Instructions.hash(bytes) == deployment.expectedHash - else { - throw ExistingGlobalConfigurationError.conflict( - "The pinned sections do not reproduce \(deployment.id). Restore the pinned " - + "sources and reconcile the recorded instruction target before previewing again.") - } - } - var expected = saved.normalized - let sourceIDs = Set( - saved.skills.values.map(\.source) + saved.instructions.sections.map(\.source) - + saved.instructions.chatgpt.values.flatMap { $0.sections.map(\.source) }) - expected.sources = expected.sources.filter { sourceIDs.contains($0.key) } - for id in expected.sources.keys { - let path = try PathSafety.sanitizeSubpath(expected.sources[id]?.path ?? ".") - expected.sources[id]?.path = path == "." ? nil : path - } - guard try prepared.domainProjection(roots: roots).normalized == expected else { - throw ExistingGlobalConfigurationError.conflict( - "The selected configuration cannot represent the recorded items or targets. " - + "Reconcile agents.json and agents.resolved before previewing again.") - } - return prepared - } - } - - private mutating func addSkill(_ name: String, locked: LockedSkill) throws { - let source = saved.sources[locked.source]! - let path = try PathSafety.sanitizeSubpath(locked.path ?? ".") - let edit = locked.installs.values.contains(.edit) - let sourceID = try addSource( - locked.source, revision: locked.revision ?? locked.artifact?.digest ?? "live", - version: locked.version) - var resource: LedgerResource - let metadata: Skill - let linkDestination: URL - if edit { - let root = URL(fileURLWithPath: String(locked.source.dropFirst("local:".count))) - let item = try contained(path, in: root) - let physical = item.resolvingSymlinksInPath() - var directory: ObjCBool = false - guard FileManager.default.fileExists(atPath: physical.path, isDirectory: &directory), - directory.boolValue - else { - throw unavailable("live skill \(name)", at: item.path) - } - let metadataFile = try contained( - path == "." ? "SKILL.md" : path + "/SKILL.md", in: root) - let edit = try EditSourceEvidence( - authoredURL: item, directory: physical, metadata: metadataFile.resolvingSymlinksInPath()) - editSources[item] = edit - metadata = try SkillOperations.lockedMetadata(at: physical, installedName: name) - resource = .init( - kind: .liveEdit, source: sourceID, path: path, - hash: edit.hash, entries: [], - location: .init(kind: .absolute, path: item.path)) - linkDestination = item - } else if let artifact = locked.artifact { - let item = try cache.artifactContentURL(digest: artifact.digest) - guard try remember(item).exists else { - throw unavailable("skill \(name)", at: item.path) - } - resource = try capture( - item, path: path, source: sourceID, expectedHash: locked.hash!, - root: item, artifact: artifact) - resource.location = try SourceCache.artifactContentLocation(digest: artifact.digest) - metadata = try SkillOperations.lockedMetadata(at: item, installedName: name) - linkDestination = item - } else { - let revision = locked.revision! - (resource, metadata) = try withPin(locked.source, source: source, revision: revision) { - conversion, root, durable in - let item = try conversion.contained(path, in: root) - let captured = try conversion.capture( - item, path: path, source: sourceID, expectedHash: locked.hash!, root: root) - if durable { try conversion.remember(captured, at: item, in: root) } - return (captured, try SkillOperations.lockedMetadata(at: item, installedName: name)) - } - linkDestination = try PathSafety.resolvedChild( - base: cache.materializedURL(sourceID: locked.source, revision: revision), subpath: path) - } - let resourceID = try storeResource(resource) - let modes = Dictionary(grouping: locked.installs.keys.sorted(), by: { locked.installs[$0]! }) - for mode in modes.keys.sorted(by: { $0.rawValue < $1.rawValue }) { - let agents = try modes[mode]!.map { raw in - guard let agent = AgentID(rawValue: raw), agent.supportsSkills else { - throw ExistingGlobalConfigurationError.conflict( - "Skill \(name) has an unsupported recipient \(raw).") - } - return agent - } - let occurrence = ledger.occurrences.count - let owner = try addComponent( - kind: .skills, name: name, source: sourceID, - revision: locked.revision, version: locked.version, - payload: [ - "name": .init(metadata.name), "description": .init(metadata.description), - "mode": .init(mode.rawValue), "native": .init(object: [:]), - ], agents: agents, prompt: nil, resource: resourceID) - for agent in agents { - let target = try store.skillInstallationTarget(for: agent, named: name) - try inspectSkill(target.url, mode: mode, resource: resource, link: linkDestination) - installations.append(target) - let id = "skill:\(occurrence):\(agent.rawValue)" - addLowering( - id: id, format: "agents/skill@1", owners: [owner], resources: [resourceID], - target: .init( - id: id, target: .init(kind: .registered, root: "skills-" + agent.rawValue, path: name), - route: "agents/skill@1", owners: [owner], recipients: [agent], ownership: .generated, - expectedHash: resource.hash, created: false, headingOffset: 0), - layout: ["name": .init(id), "mode": .init(mode.rawValue)]) - } - } - } - - private mutating func inspectSkill( - _ target: URL, mode: InstallMode, resource: LedgerResource, link: URL - ) throws { - let physical = InstructionLocations.physical(target) - if let previous = skillTargets.updateValue(mode, forKey: physical.path), previous != mode { - throw ExistingGlobalConfigurationError.conflict( - "Conflicting installation modes share \(target.path).") - } - guard try remember(target).exists else { return } - if mode == .copy { - let attributes = try FileManager.default.attributesOfItem(atPath: target.path) - let flags = Dictionary( - uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { - ($0.path, $0.executable) - }) - guard attributes[.type] as? FileAttributeType == .typeDirectory, - try "sha256:" + FileHash.folderHash(target) == resource.hash, - try FileHash.executableFlags(target) == flags - else { throw modifiedSkill(target) } - } else { - guard PathSafety.matchesSymbolicLink(at: target, destination: link) - else { throw modifiedSkill(target) } - if !FileManager.default.fileExists(atPath: target.path) { return } - } - installed.insert(physical.path) - } - - private func modifiedSkill(_ target: URL) -> ExistingGlobalConfigurationError { - .conflict( - "The skill at \(target.path) differs from its installation record. Restore the recorded " - + "contents or move the changed entry aside before previewing again.") - } - - private mutating func addInstructions() throws { - let instructions = saved.instructions - let recipients = Set(instructions.targets.values.flatMap(\.agents)) - let declared = try declaration.instructions - let agents = - (recipients.isEmpty ? Set(declared?.agents ?? declaration.defaultAgents) : recipients) - .sorted { $0.rawValue < $1.rawValue } - guard instructions.sections.isEmpty || !agents.isEmpty else { - throw ExistingGlobalConfigurationError.conflict( - "Saved instruction sections have no recipients. Reconcile the instruction selection " - + "in agents.json before previewing again.") - } - var owners: [String] = [] - for section in instructions.sections { - owners.append(try addSection(section, agents: agents)) - } - let resources = owners.map { ledger.components[$0]!.resources[0] } - for key in instructions.targets.keys.sorted() { - let target = instructions.targets[key]! - let file = try InstructionLocations.file(for: key, store: store) - let agents = target.agents.sorted { $0.rawValue < $1.rawValue } - let locations = agents.compactMap { - InstructionLocations.file(for: $0, scope: .user, environment: store.environment) - } - guard !owners.isEmpty, let agent = agents.first, Set(agents).count == agents.count, - locations.count == agents.count, - locations.allSatisfy({ InstructionLocations.physical($0) == file }) - else { - throw ExistingGlobalConfigurationError.conflict( - "The agent home settings do not resolve to the recorded target \(key). " - + "Check those settings before previewing again.") - } - let input = try TargetPrecondition.readingFile(locations[0]) - evidence[locations[0]] = input.evidence - for location in locations.dropFirst() { try remember(location) } - guard locations.allSatisfy({ InstructionLocations.physical($0) == file }) else { - throw ExistingGlobalConfigurationError.stalePreview(file.path) - } - let id = "instructions:" + key - let format: String - var layout: [String: LedgerValue] = ["name": .init(id)] - if let reference = target.import { - guard agents == [.claudeCode], - let path = ClaudeInstructionPath(rawValue: file.lastPathComponent), - reference == String(path.importLine.dropFirst()), - try input.bytes == nil - || InstructionTargets.ownedImportBytes(input.bytes).map(Instructions.hash) - == target.blockHash - else { - throw ExistingGlobalConfigurationError.conflict( - "The forwarding block at \(file.path) differs from the recorded block. " - + "Restore the recorded block before previewing again.") - } - format = "agents/claude-import@1" - } else { - format = "agents/instructions@1" - layout["headingOffset"] = .init(integer: 0) - } - addLowering( - id: id, format: format, owners: owners, resources: target.import == nil ? resources : [], - target: .init( - id: id, - target: .init( - kind: .registered, root: "instructions-" + agent.rawValue, path: file.lastPathComponent), - route: format, owners: owners, recipients: agents, - ownership: target.import == nil ? .generated : .importBlock, - expectedHash: target.blockHash, - created: target.created, importReference: target.import, - headingOffset: target.headingOffset), - layout: layout) - } - for name in instructions.chatgpt.keys.sorted() { - let prompt = instructions.chatgpt[name]! - guard !prompt.sections.isEmpty else { - throw ExistingGlobalConfigurationError.conflict( - "Locked ChatGPT prompt \(name) has no sections.") - } - var inputs: [String] = [] - for section in prompt.sections { - inputs.append(try addSection(section, agents: [], prompt: name, append: prompt.append)) - } - let id = "prompt:" + name - addLowering( - id: id, format: "agents/chatgpt@1", owners: inputs, - resources: inputs.map { ledger.components[$0]!.resources[0] }, target: nil, - layout: ["name": .init(id), "sectionCount": .init(integer: inputs.count)]) - } - } - - private mutating func addSection( - _ section: LockedSection, agents: [AgentID], prompt: String? = nil, append: String? = nil - ) throws -> String { - guard let source = saved.sources[section.source], let revision = section.revision else { - throw ExistingGlobalConfigurationError.conflict( - "Locked section \(section.name) requires a named Git source and an exact commit.") - } - let path = try PathSafety.sanitizeSubpath(section.path) - let sourceID = try addSource(section.source, revision: revision, version: section.version) - let resource = try withPin(section.source, source: source, revision: revision) { - conversion, root, durable in - let file = try conversion.contained(path, in: root) - let resource = try conversion.capture( - file, path: path, source: sourceID, expectedHash: section.hash, root: root) - if durable { try conversion.remember(resource, at: file, in: root) } - return resource - } - var payload: [String: LedgerValue] = [ - "name": .init(section.name), "sourceHash": .init(section.hash), "native": .init(object: [:]), - ] - payload["prompt"] = prompt.map { .init($0) } - if let append { - let location = LedgerLocation( - kind: .registered, root: "home", path: try PathSafety.sanitizeSubpath(append)) - payload["localAppend"] = location.ledgerValue - } - let resourceID = try storeResource(resource) - return try addComponent( - kind: .instructions, name: section.name, source: sourceID, - revision: revision, version: section.version, payload: payload, - agents: agents, prompt: prompt, resource: resourceID) - } - - private mutating func withPin( - _ identity: String, source: LockedSource, revision: String, - _ body: (inout Self, URL, Bool) throws -> T - ) throws -> T { - let sourceCache = cache - do { - return try sourceCache.withOfflineSnapshot( - sourceID: identity, source: source, revision: revision - ) { root, durable in - if !durable { - let materialized = sourceCache.materializedURL(sourceID: identity, revision: revision) - guard try !remember(materialized).exists else { - throw ExistingGlobalConfigurationError.stalePreview(materialized.path) - } - let pin = ConfigurationImportEvidence.OfflinePin( - identity: identity, source: source, revision: revision) - if !offlinePins.contains(pin) { offlinePins.append(pin) } - } - return try body(&self, root, durable) - } - } catch CoreError.notFound(let item) { - throw ExistingGlobalConfigurationError.conflict( - "Cannot read \(item) at locked commit \(revision) for \(identity). " - + "Restore the original cached content or the exact commit in the local source before retrying." - ) - } - } - - private func contained(_ path: String, in root: URL) throws -> URL { - let file = try PathSafety.resolvedChild(base: root, subpath: path) - guard PathSafety.isContained(file.resolvingSymlinksInPath(), in: root.resolvingSymlinksInPath()) - else { throw CoreError.unsafePath("locked resource escapes \(root.path)") } - return file - } - - private mutating func capture( - _ file: URL, path: String, source: String, expectedHash: String, root: URL, - artifact: LockedArtifact? = nil - ) throws -> LedgerResource { - let captured = try LedgerResources.capture( - file, embed: artifact != nil, limits: .standard, sourceRoot: root) - guard captured.hash == expectedHash else { - throw ExistingGlobalConfigurationError.conflict( - "Pinned content differs from the saved contents at \(path). Restore the matching " - + "cached content before previewing again.") - } - for (key, bytes) in captured.objects where ledger.contentObjects[key] == nil { - guard bytes.count <= LedgerLimits.standard.objectBytes - objectBytes else { - throw CoreError.invalidState("ledger aggregate content budget") - } - ledger.contentObjects[key] = bytes - objectBytes += bytes.count - } - return .init( - kind: artifact == nil ? .git : .artifact, source: source, path: path, - hash: expectedHash, entries: captured.entries, support: captured.support, artifact: artifact) - } - - @discardableResult - private mutating func remember(_ file: URL) throws -> TargetPrecondition { - if let existing = evidence[file] { return existing } - let item = try TargetPrecondition(file) - evidence[file] = item - return item - } - - private mutating func remember(_ resource: LedgerResource, at file: URL, in root: URL) throws { - try remember(file) - for entry in resource.support where entry.kind != .directory { - try remember(try contained(entry.path, in: root)) - } - } - - private func unavailable(_ name: String, at path: String) -> ExistingGlobalConfigurationError { - .conflict( - "The source for \(name) is missing at \(path). Restore the source or its cached contents " - + "and preview again.") - } - - private mutating func addSource(_ identity: String, revision: String, version: String?) throws - -> String - { - let locked = saved.sources[identity]! - let location: LedgerLocation? = - locked.kind == .local - ? .init(kind: .absolute, path: String(identity.dropFirst("local:".count))) : nil - let source = LedgerSource( - kind: locked.kind, transport: locked.kind == .wellKnown ? identity : locked.url, - location: location, revision: revision, version: version) - let id = try ResolvedLedgerCodec.digest(source) - if ledger.sources.updateValue(source, forKey: id) == nil { - ledger.sourceUses.append( - .init( - source: id, root: try PathSafety.sanitizeSubpath(locked.path ?? "."), - requirement: locked.requirement?.canonical)) - } - return id - } - - private mutating func storeResource(_ resource: LedgerResource) throws -> String { - let id = try ResolvedLedgerCodec.digest(resource) - ledger.resources[id] = resource - return id - } - - private mutating func addComponent( - kind: DeclaredComponentKind, name: String, source: String, - revision: String?, version: String?, payload: [String: LedgerValue], - agents: [AgentID], prompt: String?, resource: String - ) throws -> String { - let condition = LedgerCondition(DeclarationCondition()) - let component = LedgerComponent( - declaringSource: declaringSource, source: source, root: ".", - kind: kind.rawValue, name: name, revision: revision, version: version, - payload: .init(object: payload), conditions: [condition], recipients: agents, - chatGPT: prompt != nil, resources: [resource]) - let id = try ResolvedLedgerCodec.digest(component) - ledger.components[id] = component - ledger.occurrences.append( - .init( - declaringSource: declaringSource, manifestPath: StateStore.declarationFileName, - id: ledger.occurrences.count, component: id, dependencies: [source], - condition: condition, recipients: agents, consumerEditable: true)) - return id - } - - private mutating func addLowering( - id: String, format: String, owners: [String], resources: [String], - target: LedgerDeployment?, layout: [String: LedgerValue] - ) { - #if os(macOS) - let platform = DeclarationPlatform.macOS - #else - let platform = DeclarationPlatform.linux - #endif - if let target { ledger.deployments.append(target) } - ledger.lowerings.append( - .init( - id: id, format: format, inputs: owners, resources: resources, - deployments: target.map { [$0.id] } ?? [], layout: .init(object: layout), - platform: platform.rawValue, artifacts: [])) - } -} diff --git a/Sources/AgentsUpdates/ScopeInspection.swift b/Sources/AgentsUpdates/ScopeInspection.swift index 7503407..36949a7 100644 --- a/Sources/AgentsUpdates/ScopeInspection.swift +++ b/Sources/AgentsUpdates/ScopeInspection.swift @@ -188,7 +188,6 @@ extension UpdateOperations { var installations: [String: SkillInstallationTarget] = [:] let stateLocations = [store.declarationURL, store.resolvedURL, store.watchURL] - + [store.configurationJSONURL].compactMap { $0 } + SourcePolicySnapshot.locations(in: store).map { $0.1 } + [SourceAccessSettingsEditor.settingsURL(environment: environment)] while true { diff --git a/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift index 23998bb..ad38f71 100644 --- a/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift +++ b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift @@ -271,9 +271,7 @@ struct MappingReadLocationsTests { let expected = Set( [root, root.resolvingSymlinksInPath()].flatMap { root in let state = root.appendingPathComponent(store.scope == .project ? ".agent" : ".agents") - let userConfiguration = - store.scope == .user ? [state.appendingPathComponent("agents.json")] : [] - return [root, state] + userConfiguration + return [root, state] + [ "agents.yaml", "agents.resolved", "agents.watch", ".agents.lock", "transaction.json", "transaction.new", "watch-refs.pending", diff --git a/Tests/AgentsUpdatesTests/ExistingGlobalConfigurationTests.swift b/Tests/AgentsUpdatesTests/ExistingGlobalConfigurationTests.swift deleted file mode 100644 index 7cf2b8d..0000000 --- a/Tests/AgentsUpdatesTests/ExistingGlobalConfigurationTests.swift +++ /dev/null @@ -1,688 +0,0 @@ -import AgentsInstructions -import AgentsManifest -import AgentsSkills -import AgentsUpdates -import Foundation -import StateTestSupport -import Testing - -@testable import AgentsCore - -@Suite("Use Existing Configuration") -struct ExistingGlobalConfigurationTests { - @Test func recognitionAndCancellationNeedNoWrites() throws { - let f = try UpdateFixture(scope: .user) - let empty = try FileHash.folderHash(f.environment.homeDirectory) - #expect(try !ExistingGlobalConfiguration.isAvailable(environment: f.environment)) - #expect(try FileHash.folderHash(f.environment.homeDirectory) == empty) - let json = try #require(f.store.configurationJSONURL) - try f.write("{}", to: json) - #expect(try !ExistingGlobalConfiguration.isAvailable(environment: f.environment)) - try ResolvedLedgerCodec.encode(ResolvedLedger(), limits: .standard).write( - to: f.store.resolvedURL) - #expect(try !ExistingGlobalConfiguration.isAvailable(environment: f.environment)) - try StateStore.encodeState(ResolvedState()).write(to: f.store.resolvedURL) - let before = try FileHash.folderHash(f.environment.homeDirectory) - #expect(try ExistingGlobalConfiguration.isAvailable(environment: f.environment)) - let cancelled = try ExistingGlobalConfiguration.preview(environment: f.environment) - #expect(cancelled.skillCount == 0) - #expect(cancelled.declarationURL == f.store.declarationURL) - #expect(try FileHash.folderHash(f.environment.homeDirectory) == before) - #expect(!FileManager.default.fileExists(atPath: cancelled.originalLedgerURL.path)) - #expect( - !FileManager.default.fileExists( - atPath: f.store.directory.appendingPathComponent(".agents.lock").path)) - } - - @Test func importsIndependentPinsAndInspectsActualNativeInstalls() throws { - let input = try ExistingProfile() - let f = input.fixture - let before = try f.snapshot() - let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) - #expect(preview.sourceCount == 2) - #expect(preview.skillCount == 2) - #expect(preview.installationCount == 2) - #expect(preview.instructionCount == 2) - #expect(preview.originalLedgerURL.lastPathComponent == "agents.resolved.original") - #expect(try f.snapshot() == before) - try ExistingGlobalConfiguration.apply(preview) - #expect(try f.bytes(input.json) == input.declarationBytes) - #expect(try f.bytes(preview.originalLedgerURL) == input.lockBytes) - #expect(try f.bytes(f.store.watchURL) == input.watchBytes) - #expect(try !ExistingGlobalConfiguration.isAvailable(environment: f.environment)) - let declaration = try f.store.loadDeclaration() - #expect(declaration.agents == [.codex, .claudeCode]) - #expect(try declaration.skills?["fixture"]?.select == .all) - #expect(try declaration.skills?["fixture"]?.exclude == ["excluded"]) - let override = try #require(try declaration.skills?["fixture"]?.overrides?["demo"]) - #expect(override.mode == .link) - #expect(override.agents == [.codex, .geminiCLI, .claudeCode]) - #expect(try declaration.instructions?.sections == ["fixture:rules"]) - #expect(try declaration.instructions?.chatgpt?["weekly"]?.append == "custom.md") - #expect(try declaration.skills?["live"]?.select == .names(["edit-demo", "uninstalled"])) - #expect(declaration.watch == ["fixture"]) - #expect(try f.store.loadResolved().normalized == input.expected.normalized) - let snapshot = try UpdateOperations.inspect(scope: .user, environment: f.environment) - #expect(snapshot.readLocations.contains(input.json)) - #expect( - snapshot.components.first { $0.kind == .skills && $0.name == "demo" }?.version == "1.2.0") - #expect(snapshot.components.first { $0.kind == .instructions }?.version == "1.3.0") - let skills = snapshot.deployments.filter { $0.format == "agents/skill@1" } - #expect(skills.filter { $0.status == .current }.count == 3) - #expect(skills.filter { $0.status == .missing }.count == 1) - #expect(snapshot.deployments.first { $0.format == "agents/instructions@1" }?.status == .drifted) - #expect( - snapshot.deployments.first { $0.format == "agents/claude-import@1" }?.status == .current) - #expect(try f.bytes(f.instruction()) == Data("Edited outside agents.\n".utf8)) - let statePaths = [f.store.declarationURL.path, f.store.resolvedURL.path] - #expect( - try f.snapshot().filter { !statePaths.contains($0.key) } - == before.filter { !statePaths.contains($0.key) }) - } - - @Test(arguments: [true, false]) - func importedArtifactUsesItsRetainedLocation(_ includeRemote: Bool) throws { - let f = try UpdateFixture(scope: .user) - let cache = SourceCache(store: f.store) - let pin = try f.git(["rev-parse", "HEAD"]) - let remote = "example.invalid/remote" - let gitTree = cache.materializedURL(sourceID: remote, revision: pin) - let remoteSkill = gitTree.appendingPathComponent("skills/demo") - let content = try f.bytes(f.repo.appendingPathComponent("skills/demo/SKILL.md")) - try f.write( - String(decoding: content, as: UTF8.self), to: remoteSkill.appendingPathComponent("SKILL.md")) - let artifactBytes = Data( - "---\nname: index-demo\ndescription: Index fixture\n---\n\nBody\n".utf8) - let index = "https://index.example.invalid" - let artifact = LockedArtifact( - type: .skillMD, url: index + "/demo/SKILL.md", - digest: "sha256:" + FileHash.sha256Hex(data: artifactBytes)) - let artifactTree = try cache.artifactContentURL(digest: artifact.digest) - try f.write( - String(decoding: artifactBytes, as: UTF8.self), - to: artifactTree.appendingPathComponent("SKILL.md")) - try FileManager.default.createDirectory( - at: f.target().deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.createSymbolicLink( - at: f.target(), withDestinationURL: remoteSkill.resolvingSymlinksInPath()) - let artifactInstall = f.target().deletingLastPathComponent().appendingPathComponent( - "index-demo") - try FileManager.default.createSymbolicLink( - at: artifactInstall, withDestinationURL: artifactTree) - let artifactLink = try PathIdentity(artifactInstall) - var lock = ResolvedState( - sources: [ - remote: .init(kind: .git, url: "https://" + remote), - index: .init(kind: .wellKnown), - ], - skills: [ - "demo": .init( - source: remote, revision: pin, path: "skills/demo", - hash: try "sha256:" + FileHash.folderHash(remoteSkill), installs: ["codex": .link]), - "index-demo": .init( - source: index, artifact: artifact, - hash: try "sha256:" + FileHash.folderHash(artifactTree), installs: ["codex": .link]), - ]) - if !includeRemote { - try FileManager.default.removeItem(at: f.target()) - try FileManager.default.removeItem(at: gitTree) - lock.sources.removeValue(forKey: remote) - lock.skills.removeValue(forKey: "demo") - } - let remoteSource = includeRemote ? "\"remote\":{\"git\":\"https://\(remote)\"}," : "" - let remoteSelection = includeRemote ? "\"remote\":{\"select\":[\"demo\"]}," : "" - let json = try #require(f.store.configurationJSONURL) - try f.write( - """ - {"agents":["codex"],"sources":{\(remoteSource)"index":{"well-known":"\(index)"}}, - "skills":{\(remoteSelection)"index":{"select":["index-demo"],"mode":"link"}}} - """, to: json) - try StateStore.encodeState(lock).write(to: f.store.resolvedURL) - let cacheHash = try FileHash.folderHash(f.store.cacheDirectory) - let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) - #expect(preview.installationCount == lock.skills.count) - try ExistingGlobalConfiguration.apply(preview) - #expect(try f.store.loadResolved().normalized == lock.normalized) - #expect(try FileHash.folderHash(f.store.cacheDirectory) == cacheHash) - let inventory = try UpdateOperations.inspect(scope: .user, environment: f.environment) - #expect( - inventory.deployments.map(\.status) == Array(repeating: .current, count: lock.skills.count)) - #expect( - inventory.resources.first { $0.kind == "artifact" }?.location?.path == artifactTree.path) - let restore = UpdateRequest(operation: .restore, kinds: [.skills]) - let report = try UpdateOperations.preview(restore, scope: .user, environment: f.environment) - try #require(!report.hasChanges) - _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) - try artifactLink.validate() - #expect(try FileHash.folderHash(f.store.cacheDirectory) == cacheHash) - - if !includeRemote { - let declaration = try f.store.loadDeclaration() - _ = try UpdateOperations.withPreparedUpdate( - UpdateRequest(operation: .declaration(declaration)), scope: .user, - environment: f.environment - ) { try $0.apply() } - try artifactLink.validate() - let reapplied = try UpdateOperations.inspect(scope: .user, environment: f.environment) - #expect(reapplied.resources.first?.location?.path == artifactTree.path) - - try FileManager.default.removeItem(at: artifactTree) - _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) - try artifactLink.validate() - #expect(try f.bytes(artifactTree.appendingPathComponent("SKILL.md")) == artifactBytes) - let restored = try UpdateOperations.inspect(scope: .user, environment: f.environment) - #expect(restored.resources.first?.location?.path == artifactTree.path) - #expect(restored.deployments.map(\.status) == [.current]) - - var invalid = try f.store.loadLedger() - let id = try #require(invalid.resources.first { $0.value.kind == .artifact }?.key) - invalid.resources[id]?.location = .init(kind: .registered, root: "state", path: "cache/other") - #expect(throws: CoreError.self) { - _ = try ResolvedLedgerCodec.encode(invalid, limits: .standard) - } - } - } - - @Test func importsAndInspectsLargeLiveEditSourceWithoutReplacingTheLink() throws { - let f = try UpdateFixture(scope: .user) - let directory = f.repo.appendingPathComponent("skills/demo").resolvingSymlinksInPath() - let blob = directory.appendingPathComponent("references/blob") - try f.write("", to: blob) - let length = UInt64(max(180 * 1024 * 1024, LedgerLimits.standard.resourceBytes)) + 1 - do { - let handle = try FileHandle(forWritingTo: blob) - defer { try? handle.close() } - try handle.truncate(atOffset: length) - } - try FileManager.default.createDirectory( - at: f.target().deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.createSymbolicLink(at: f.target(), withDestinationURL: directory) - let targetIdentity = try PathIdentity(f.target()) - let sourceIdentity = "local:" + f.repo.path - let json = try #require(f.store.configurationJSONURL) - try f.write( - """ - {"sources":{"fixture":{"local":"\(f.repo.path)"}}, - "skills":{"fixture":{"select":["demo"],"agents":["codex"],"mode":"edit"}}} - """, to: json) - let saved = ResolvedState( - sources: [sourceIdentity: .init(kind: .local)], - skills: [ - "demo": .init(source: sourceIdentity, path: "skills/demo", installs: ["codex": .edit]) - ]) - let lockBytes = try StateStore.encodeState(saved) - try lockBytes.write(to: f.store.resolvedURL) - - let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) - #expect(preview.skillCount == 1) - #expect(preview.installationCount == 1) - try ExistingGlobalConfiguration.apply(preview) - try targetIdentity.validate() - #expect(try f.bytes(preview.originalLedgerURL) == lockBytes) - #expect(try f.store.loadResolved() == saved) - - let snapshot = try UpdateOperations.inspect(scope: .user, environment: f.environment) - #expect(snapshot.components.map(\.name) == ["demo"]) - #expect(snapshot.deployments.map(\.status) == [.current]) - let resource = try #require(snapshot.resources.first) - #expect(resource.kind == "liveEdit") - #expect(resource.location?.resolvingSymlinksInPath().path == directory.path) - #expect(resource.entries.isEmpty) - #expect(snapshot.readLocations.contains { $0.resolvingSymlinksInPath().path == directory.path }) - let attributes = try FileManager.default.attributesOfItem(atPath: blob.path) - #expect((attributes[.size] as? NSNumber)?.uint64Value == length) - } - - @Test(arguments: ["declaration", "native", "cache", "edit-source", "edit-link", "backup", "yaml"]) - func confirmationRejectsStaleEvidence(_ changed: String) throws { - let input = try ExistingProfile() - let f = input.fixture - let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) - switch changed { - case "declaration": try f.write("{}\n", to: input.json) - case "native": try f.write("New native bytes\n", to: f.instruction()) - case "cache": - try f.write( - "Pinned resource changed\n", to: input.pinnedSkill.appendingPathComponent("run.sh")) - case "edit-source": - try f.write( - "New reference data\n", to: f.root.appendingPathComponent("live/edit-demo/references.txt")) - case "edit-link": - let link = f.target().deletingLastPathComponent().appendingPathComponent("edit-demo") - try FileManager.default.removeItem(at: link) - try FileManager.default.createSymbolicLink(at: link, withDestinationURL: f.repo) - case "backup": try f.write("Retained lock copy\n", to: preview.originalLedgerURL) - default: try f.write("version: 1\n", to: f.store.declarationURL) - } - let before = try FileHash.folderHash(f.environment.homeDirectory) - #expect(throws: ExistingGlobalConfigurationError.self) { - try ExistingGlobalConfiguration.apply(preview) - } - let after = try FileManager.default.contentsOfDirectory(atPath: f.store.directory.path) - #expect(!after.contains("transaction.json")) - #expect(try f.bytes(f.store.resolvedURL) == input.lockBytes) - #expect(try FileHash.folderHash(f.environment.homeDirectory) == before) - if changed == "backup" { - #expect(try f.bytes(preview.originalLedgerURL) == Data("Retained lock copy\n".utf8)) - } - } - - @Test func aChangedSkillIsAnExplicitConflict() throws { - let input = try ExistingProfile() - let f = input.fixture - let changed = f.target(.claudeCode) - try f.write("Unrelated directory\n", to: changed.appendingPathComponent("SKILL.md")) - #expect(try ExistingGlobalConfiguration.isAvailable(environment: f.environment)) - do { - _ = try ExistingGlobalConfiguration.preview(environment: f.environment) - Issue.record("Imported a skill path with unrelated contents") - } catch let error as ExistingGlobalConfigurationError { - #expect(error.localizedDescription.contains(changed.path)) - #expect(error.localizedDescription.contains("move the changed entry aside")) - } - #expect(try f.bytes(f.store.resolvedURL) == input.lockBytes) - } - - @Test func pendingOperationTakesPriorityOverRecognitionAndPreview() throws { - let f = try UpdateFixture(scope: .user) - try f.write("{}", to: f.store.directory.appendingPathComponent("transaction.json")) - for operation in [ - { _ = try ExistingGlobalConfiguration.isAvailable(environment: f.environment) }, - { _ = try ExistingGlobalConfiguration.preview(environment: f.environment) }, - ] { - do { - try operation() - Issue.record("Inspected a scope with a pending operation") - } catch let error as ExistingGlobalConfigurationError { - guard case .recovery = error else { - Issue.record(error) - continue - } - #expect(error.localizedDescription.contains("Finish it in the tool that started it")) - } - } - #expect( - try f.bytes(f.store.directory.appendingPathComponent("transaction.json")) == Data("{}".utf8)) - } - - @Test(arguments: [false, true]) - func retargetedInstallationRootInvalidatesConfirmation(_ duringPublication: Bool) throws { - let input = try ExistingProfile() - let f = input.fixture - let parent = f.target().deletingLastPathComponent() - let inspected = f.store.directory.appendingPathComponent("inspected-skills") - let other = f.store.directory.appendingPathComponent("other-skills") - try FileManager.default.moveItem(at: parent, to: inspected) - try FileManager.default.createDirectory(at: other, withIntermediateDirectories: false) - try FileManager.default.createSymbolicLink(at: parent, withDestinationURL: inspected) - let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) - let nativeBefore = try FileHash.folderHash(inspected) - func redirect() throws { - try FileManager.default.removeItem(at: parent) - try FileManager.default.createSymbolicLink(at: parent, withDestinationURL: other) - } - if !duringPublication { try redirect() } - - #expect(throws: ExistingGlobalConfigurationError.self) { - try ExistingGlobalConfiguration.apply(preview) { checkpoint in - if duringPublication, checkpoint == TransactionCheckpoint.progress(2, .applied).name { - try redirect() - } - } - } - #expect(try FileHash.folderHash(inspected) == nativeBefore) - #expect(try FileManager.default.contentsOfDirectory(atPath: other.path).isEmpty) - try expectUnapplied(preview, ledger: input.lockBytes, fixture: f) - } - - @Test func staleConfirmationLeavesPendingNativeRecoveryForItsOwner() throws { - let input = try ExistingProfile() - let f = input.fixture - let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) - try ExistingGlobalConfiguration.apply(preview) - let native = f.target().deletingLastPathComponent().appendingPathComponent("target/SKILL.md") - try f.write("installed content\n", to: native) - try f.write("partly published content\n", to: f.root.appendingPathComponent("new/SKILL.md")) - let child = try launch( - f, command: "inspection-transaction", - argument: TransactionCheckpoint.progress(0, .applied).name) - defer { terminate(child) } - try waitFor("ready", fixture: f, child: child) - terminate(child) - - let journal = f.store.directory.appendingPathComponent("transaction.json") - let pending = try f.bytes(journal) - #expect(try f.bytes(native) == Data("partly published content\n".utf8)) - do { - try ExistingGlobalConfiguration.apply(preview) - Issue.record("Confirmed configuration during native recovery") - } catch let error as ExistingGlobalConfigurationError { - guard case .recovery = error else { - Issue.record(error) - return - } - } - #expect(try f.bytes(journal) == pending) - #expect(try f.bytes(native) == Data("partly published content\n".utf8)) - #expect(throws: CoreError.transactionRecovered(f.store.directory.path)) { - try f.store.withLock {} - } - #expect(try f.bytes(native) == Data("installed content\n".utf8)) - } - - @Test(arguments: [ - TransactionCheckpoint.preconditions.name, TransactionCheckpoint.progress(2, .applied).name, - ]) - func lostOfflinePinAbortsConfirmation(_ point: String) throws { - let input = try ExistingProfile() - let f = input.fixture - let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) - let displaced = f.root.appendingPathComponent("displaced-source") - #expect(throws: ExistingGlobalConfigurationError.self) { - try ExistingGlobalConfiguration.apply(preview) { checkpoint in - if checkpoint == point { try FileManager.default.moveItem(at: f.repo, to: displaced) } - } - } - #expect(FileManager.default.fileExists(atPath: displaced.path)) - try expectUnapplied(preview, ledger: input.lockBytes, fixture: f) - } - - @Test(arguments: ["\"team\"", "null"]) - func rejectsUnsupportedSkillSelectionPath(_ path: String) throws { - let f = try UpdateFixture(scope: .user) - let json = try #require(f.store.configurationJSONURL) - try f.write( - """ - {"sources":{"team":{"git":"example.invalid/team","path":"skills"}}, - "skills":{"team":{"select":"all","path":\(path)}}} - """, to: json) - try StateStore.encodeState(ResolvedState()).write(to: f.store.resolvedURL) - do { - _ = try ExistingGlobalConfiguration.preview(environment: f.environment) - Issue.record("Accepted an unsupported skill selection path") - } catch let error as ExistingGlobalConfigurationError { - #expect(error.localizedDescription.contains("skills.team.path is unsupported")) - #expect(error.localizedDescription.contains("sources.team.path")) - } - } - - @Test func preservesSourceDiscoveryPathAndSelection() throws { - let f = try UpdateFixture(scope: .user) - let json = try #require(f.store.configurationJSONURL) - try f.write( - """ - {"sources":{"team":{"git":"example.invalid/team","path":"skills/team"}}, - "skills":{"team":{"select":"all","exclude":["retired"],"overrides":{"current":{"mode":"copy"}}}}} - """, to: json) - try StateStore.encodeState(ResolvedState()).write(to: f.store.resolvedURL) - try ExistingGlobalConfiguration.apply( - ExistingGlobalConfiguration.preview(environment: f.environment)) - - let declaration = try f.store.loadDeclaration() - #expect(declaration.sources["team"]?.path == "skills/team") - let selection = try #require(try declaration.skills?["team"]) - #expect(selection.select == .all) - #expect(selection.path == nil) - #expect(selection.exclude == ["retired"]) - #expect(selection.overrides?["current"]?.mode == .copy) - } - - @Test func rejectsAliasesForOneNormalizedSourceWithDistinctRoots() throws { - let f = try UpdateFixture(scope: .user) - let json = try #require(f.store.configurationJSONURL) - try f.write( - """ - {"sources":{"team":{"git":"https://example.invalid/shared.git","path":"team"}, - "tools":{"git":"https://example.invalid/shared","path":"tools"}}} - """, to: json) - try StateStore.encodeState(ResolvedState()).write(to: f.store.resolvedURL) - do { - _ = try ExistingGlobalConfiguration.preview(environment: f.environment) - Issue.record("Accepted two aliases for one saved source identity") - } catch let error as ExistingGlobalConfigurationError { - #expect(error.localizedDescription.contains("'team' and 'tools'")) - #expect(error.localizedDescription.contains("Use one alias per source")) - } - } - - @Test func reopensAnEditLinkThroughItsAuthoredSourceAlias() throws { - let f = try UpdateFixture(scope: .user) - let alias = try importEditAlias(f) - let installed = try PathIdentity(f.target()) - let alternate = f.repo.appendingPathComponent("skills/alternate") - try FileManager.default.copyItem( - at: f.repo.appendingPathComponent("skills/demo"), to: alternate) - try FileManager.default.removeItem(at: alias) - try FileManager.default.createSymbolicLink(atPath: alias.path, withDestinationPath: "alternate") - - let inventory = try UpdateOperations.inspect(scope: .user, environment: f.environment) - #expect(inventory.deployments.map(\.status) == [.current]) - #expect(inventory.resources.first?.location?.path == alias.path) - _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) - try installed.validate() - #expect( - try FileManager.default.destinationOfSymbolicLink(atPath: f.target().path) == alias.path) - } - - @Test(arguments: [false, true]) - func declinesAnEditAliasRetargetedOutsideItsSource(_ afterPreparation: Bool) throws { - let f = try UpdateFixture(scope: .user) - let alias = try importEditAlias(f) - let installed = try PathIdentity(f.target()) - let ledger = try f.bytes(f.store.resolvedURL) - let outside = f.root.appendingPathComponent("outside") - try FileManager.default.copyItem(at: f.repo.appendingPathComponent("skills/demo"), to: outside) - func retarget() throws { - try FileManager.default.removeItem(at: alias) - try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: outside) - } - if !afterPreparation { try retarget() } - do { - if afterPreparation { - _ = try UpdateOperations.withPreparedUpdate( - UpdateRequest(operation: .restore, kinds: [.skills]), scope: .user, - environment: f.environment - ) { prepared in - try retarget() - return try prepared.apply() - } - } else { - _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) - } - Issue.record("Restored an edit source outside its recorded source directory") - } catch { - let cause = (error as? UpdateApplyError)?.underlyingError ?? error - guard case CoreError.unsafePath(let message) = cause else { - Issue.record(error) - return - } - #expect(message.contains("outside its recorded source directory")) - #expect(message.contains("Point the source alias inside")) - } - - let inventory = try UpdateOperations.inspect(scope: .user, environment: f.environment) - let deployment = try #require(inventory.deployments.first) - #expect(deployment.status == .drifted) - #expect(deployment.diagnostic?.contains("Point the source alias inside") == true) - #expect(inventory.resources.first?.location?.path == alias.path) - #expect(try f.bytes(f.store.resolvedURL) == ledger) - try installed.validate() - #expect( - try FileManager.default.destinationOfSymbolicLink(atPath: f.target().path) == alias.path) - #expect(try FileManager.default.destinationOfSymbolicLink(atPath: alias.path) == outside.path) - } - - private func importEditAlias(_ f: UpdateFixture) throws -> URL { - let alias = f.repo.appendingPathComponent("skills/current") - try FileManager.default.createSymbolicLink(atPath: alias.path, withDestinationPath: "demo") - let target = f.target() - try FileManager.default.createDirectory( - at: target.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.createSymbolicLink(at: target, withDestinationURL: alias) - let json = try #require(f.store.configurationJSONURL) - try f.write( - """ - {"sources":{"fixture":{"local":"\(f.repo.path)"}}, - "skills":{"fixture":{"select":["demo"],"agents":["codex"],"mode":"edit"}}} - """, to: json) - let identity = "local:" + f.repo.path - let saved = ResolvedState( - sources: [identity: .init(kind: .local)], - skills: ["demo": .init(source: identity, path: "skills/current", installs: ["codex": .edit])]) - try StateStore.encodeState(saved).write(to: f.store.resolvedURL) - try ExistingGlobalConfiguration.apply( - ExistingGlobalConfiguration.preview(environment: f.environment)) - return alias - } - - @Test(arguments: [ - TransactionCheckpoint.progress(1, .applied).name, TransactionCheckpoint.phase(.committed).name, - ]) - func recoveryAfterKilledWriterKeepsOneGeneration(_ point: String) throws { - let input = try ExistingProfile() - let f = input.fixture - let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) - let child = try launch(f, command: "existing-configuration", argument: point) - defer { terminate(child) } - try waitFor("ready", fixture: f, child: child) - terminate(child) - let pending = try UpdateOperations.inspect(scope: .user, environment: f.environment) - #expect(pending.recovery.pending) - #expect(pending.readLocations.contains(input.json)) - #expect(throws: ExistingGlobalConfigurationError.self) { - try ExistingGlobalConfiguration.preview(environment: f.environment) - } - #expect(throws: CoreError.transactionRecovered(f.store.directory.path)) { - try f.store.withLock {} - } - if point == TransactionCheckpoint.phase(.committed).name { - #expect(try f.store.loadResolved().normalized == input.expected.normalized) - #expect(try f.bytes(preview.originalLedgerURL) == input.lockBytes) - } else { - #expect(try f.bytes(f.store.resolvedURL) == input.lockBytes) - #expect(try ExistingGlobalConfiguration.isAvailable(environment: f.environment)) - #expect(!FileManager.default.fileExists(atPath: preview.originalLedgerURL.path)) - try ExistingGlobalConfiguration.apply( - ExistingGlobalConfiguration.preview(environment: f.environment)) - } - #expect(try f.bytes(input.json) == input.declarationBytes) - #expect(try f.bytes(f.store.watchURL) == input.watchBytes) - } - - private func expectUnapplied( - _ preview: ExistingGlobalConfigurationPreview, ledger: Data, fixture: UpdateFixture - ) throws { - #expect(try fixture.bytes(preview.ledgerURL) == ledger) - #expect(!FileManager.default.fileExists(atPath: preview.declarationURL.path)) - #expect(!FileManager.default.fileExists(atPath: preview.originalLedgerURL.path)) - #expect(try ExistingGlobalConfiguration.isAvailable(environment: fixture.environment)) - } -} - -private struct ExistingProfile { - let fixture: UpdateFixture - let json: URL - let declarationBytes: Data - let lockBytes: Data - let watchBytes: Data - let expected: ResolvedState - let pinnedSkill: URL - - init() throws { - let f = try UpdateFixture(scope: .user) - fixture = f - json = try #require(f.store.configurationJSONURL) - let cache = SourceCache(store: f.store) - let identity = "local:" + f.repo.path - let skillRevision = try f.git(["rev-parse", "HEAD"]) - let materialized = cache.materializedURL(sourceID: identity, revision: skillRevision) - pinnedSkill = materialized.appendingPathComponent("skills/demo") - try FileManager.default.createDirectory( - at: pinnedSkill.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.copyItem( - at: f.repo.appendingPathComponent("skills/demo"), to: pinnedSkill) - try FileManager.default.setAttributes( - [.posixPermissions: 0o755], ofItemAtPath: pinnedSkill.appendingPathComponent("run.sh").path) - try FileManager.default.createDirectory( - at: f.target().deletingLastPathComponent(), withIntermediateDirectories: true) - let relative = PathSafety.relativePath(pinnedSkill.path, to: f.store.directory.path) - try FileManager.default.createSymbolicLink( - atPath: f.target().path, withDestinationPath: "../" + relative) - - try f.advance() - let instructionRevision = try f.git(["rev-parse", "HEAD"]) - let instructionBytes = try f.bytes(f.repo.appendingPathComponent("instructions/rules.md")) - try f.writeSource("later HEAD and dirty working tree") - try f.commit() - try f.writeSource("dirty") - let section = LockedSection( - name: "rules", source: identity, revision: instructionRevision, version: "1.3.0", - path: "instructions/rules.md", hash: Instructions.hash(instructionBytes)) - let rendered = try Instructions.render([ - Instructions.validateSource(instructionBytes, id: "rules") - ]) - try f.write("Edited outside agents.\n", to: f.instruction()) - let forwarding = ClaudeForwarding.renderBlock(for: .root) - try f.write("Custom prose\n\n" + forwarding, to: f.instruction(.claudeCode)) - - let live = f.root.appendingPathComponent("live") - let edit = live.appendingPathComponent("edit-demo") - try f.write( - "---\nname: edit-demo\ndescription: Live fixture\n---\n\nNew live content\n", - to: edit.appendingPathComponent("SKILL.md")) - try FileManager.default.createSymbolicLink( - at: f.target().deletingLastPathComponent().appendingPathComponent("edit-demo"), - withDestinationURL: edit.resolvingSymlinksInPath()) - let editIdentity = "local:" + live.path - let unused = "example.invalid/unused" - var lock = ResolvedState( - sources: [ - identity: .init(kind: .local, requirement: .branch("main")), - editIdentity: .init(kind: .local), - unused: .init(kind: .git, url: "https://" + unused), - ], - skills: [ - "demo": .init( - source: identity, revision: skillRevision, version: "1.2.0", path: "skills/demo", - hash: try "sha256:" + FileHash.folderHash(pinnedSkill), - installs: ["codex": .link, "gemini-cli": .link, "claude-code": .link]), - "edit-demo": .init(source: editIdentity, path: "edit-demo", installs: ["codex": .edit]), - ], - instructions: .init( - sections: [section], chatgpt: ["weekly": .init(sections: [section], append: "custom.md")], - targets: [ - InstructionLocations.key(for: f.instruction(), store: f.store): .init( - agents: [.codex], headingOffset: 0, blockHash: Instructions.hash(Data(rendered.utf8)), - created: true), - InstructionLocations.key(for: f.instruction(.claudeCode), store: f.store): .init( - agents: [.claudeCode], import: "AGENTS.md", - blockHash: Instructions.hash(Data(forwarding.utf8)), created: false), - ])) - lockBytes = try StateStore.encodeState(lock) - try lockBytes.write(to: f.store.resolvedURL) - lock.sources.removeValue(forKey: unused) - expected = lock - watchBytes = Data("{ \"version\": 1, \"sources\": {} }\n".utf8) - try watchBytes.write(to: f.store.watchURL) - declarationBytes = Data( - """ - { - "agents": ["codex","claude-code"], - "sources": { - "fixture": {"local": "\(f.repo.path)", "branch": "main"}, - "live": {"local": "\(live.path)"} - }, - "skills": { - "fixture": {"select":"all","exclude":["excluded"],"mode":"copy", - "overrides":{"demo":{"agents":["codex","gemini-cli","claude-code"],"mode":"link"}}}, - "live": {"select":["edit-demo","uninstalled"],"agents":["codex"],"mode":"edit"} - }, - "instructions": {"agents":["codex"],"sections":["fixture:rules"], - "chatgpt":{"weekly":{"sections":["fixture:rules"],"append":"custom.md"}}}, - "watch": ["fixture"] - } - - """.utf8) - try declarationBytes.write(to: json) - } -} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 74ec142..77e57e4 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -120,9 +120,6 @@ if arguments[2].hasPrefix("acquisition-") { root: root, input: URL(fileURLWithPath: arguments[4]), checkpoint: { try stop($0) }) } else if arguments[2].hasPrefix("ledger-") { try ledgerProbe(arguments[2], store: store) -} else if arguments[2] == "existing-configuration" { - let preview = try ExistingGlobalConfiguration.preview(environment: store.environment) - try ExistingGlobalConfiguration.apply(preview, checkpoint: { try stop($0) }) } else if arguments[2].hasPrefix("shared-") { try sharedMaterializationProbe(arguments[2], store: store, checkpoint: { try stop($0) }) } else if arguments[2].hasPrefix("private-") {