diff --git a/CHANGELOG.md b/CHANGELOG.md index dce8e22..26cd007 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## 0.3.3 + +### Fixed + +- Materialize only the Git files needed by the resolved ledger. Combined updates + retire oversized and expired pins in the same transaction as deployments. +- Preserve live-edit skill paths during filtered updates and pin maintenance. +- Store exact Git instruction and include coordinates for Antigravity rules. + Existing self-contained locks can still restore their outputs offline. +- Check locked instruction bodies, includes and prompt inputs independently of + deployed files during doctor audits. + ## 0.3.2 ### Added diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 108a8d7..e905bac 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -300,7 +300,7 @@ the denial. Existing user content and metadata are preserved. ### Journal records -Journal format version 3 is independent of the manifest language, lock and watch +Journal format version 4 is independent of the manifest language, lock and watch versions. The root records its version, transaction UUID, scope identity, registered root identities, transaction phase, operations, private containers, disposal @@ -361,6 +361,7 @@ terminal disposal evidence after their expected distribution has been verified. | `restoring` | Undo and temporary directory-write intent; installed or reverted objects can be present. | | `restored` | Undo parents and original modes synced; restored target and remaining slot objects verified. | | `cancelled` | Original modes restored; publication did not consume private staging. | +| `skipped` | Deferred ledger evidence matched its preimage. No replacement is staged. Commit and committed recovery require the original ledger. | One operation-type/progress table defines every expected target and recovery slot. Publication validation, rollback classification and disposal preparation @@ -731,15 +732,22 @@ consumer error contract. ## Materialization and Installation -Git materializations, downloaded artifact bytes and expanded artifact trees use -private journal-owned staging. Exact Git commits are extracted there; expanded -artifacts are checked against their locked tree hash. Copied trees are hashed -through pinned directory descriptors and verified before publication. Files, -metadata and directory entries are synced before atomic publication of the final -cache name. Git extraction work also belongs to the journal, so recovery -cleans an incomplete copy or extraction without retaining a partial final -directory just because the lock references its pin. Cache publication completes -before the installation transaction references that content. +Git pins, downloaded artifacts and expanded artifact trees use private +journal-owned staging. The ledger groups Git resources by root source identity +and exact commit. The resulting pin includes the selected trees, link targets, +traversed links, and structural directories required to reach them. Structural +directories can be empty. Cache replacements and deletions publish in the same +transaction as deployments and the ledger. + +The transaction streams file evidence for an ordinary directory preimage at an +admitted materialized pin. Recovery uses the journal's destination, the legal +slot layout and the recorded inode to identify that preimage. The same tree +and format limits apply to both evidence paths. Before the first publication, +the transaction removes prepared work and admits the terminal container reads +and journal encoding, including space to persist conflicts. Partial disposal +accepts surviving directories at their original mode or with owner access +added by disposal. It verifies every surviving entry through its opened +parent before unlinking it. Each scope's cache contains: @@ -752,13 +760,22 @@ cache/ locks/ ``` -A source key combines a readable prefix and the SHA-256 of its normalized ID. A -source has one bare mirror; requirement resolution reads its refs and tags. -Exact trees are extracted with Git archive and contain no repository metadata. -Read-only revision inspection uses local Git reads or remote ref advertisements -with the same requirement selection policy, without fetching or populating -caches. Consumers of the same source and revision share a materialized -directory. +A source key combines a readable prefix and the SHA-256 of its normalized ID. +A source has one bare mirror. Local discovery freezes the transport's ref and +HEAD advertisement and borrows the local object store in a temporary catalog. +Catalog refs retain their own namespace. Exact trees use a private archive +repository with a fixed unborn HEAD and committed attributes. The archive reader +walks committed tree entries before selecting paths. Stateful substitutions use +the full archive order, while extraction retains only the selected entries. +Replay checks selected hashes and compares coordinate-only support files with +their exact archive bytes. + +A source session expands an address-stable workspace when discovery or replay +requires another path at the same pin. Looking up the repository root for +containment leaves the selection unchanged. Explicit root discovery and root +directory resources select the root recursively. Read-only operations keep +temporary acquisition disposable and leave mirrors and materialized pins +unchanged. `link` points an agent's skill entry at verified cached content. `copy` installs that content as a directory and rejects links escaping the installed subtree. @@ -789,12 +806,23 @@ once. The synchronous prepared handle retains these borrowed resources and write locks while the consumer renders its report and applies it. Live edit content stays live; its identity and usable metadata are checked instead of a content pin. -Apply validates state, targets and source evidence, retains the complete ledger/watch -reference closure, and validates again. One transaction stages resource trees and -capsules, selected physical targets, declaration, ledger, receipts and cache pruning. -No-change apply returns receipts without rewriting state. Exiting before apply -publishes no targets, state or retained trees; writer lock containers may remain. -Temporary source and replay resources are released at closure exit. +Preparation decides which pins will be created, replaced, kept or deleted. +The report fingerprint binds those decisions, the candidate closure and the +recorded generation of each pin that will move. A combined update can retire +expired pins or shrink an older pin to its verified closure. Filtered updates +prepare pins needed by the selected changes. Restore can recreate a missing +pin even when the deployed target already matches. The active and pending +closures protect authored live-edit links and verified editable directories +from pin deletion and replacement. + +Apply revalidates state, targets and source evidence. It acquires required +Git objects and applies a single object-store barrier per mirror before +publishing the retention refs. One transaction stages pin changes, resource +capsules, selected targets, declaration, ledger, receipts and artifact pruning. +Private native outputs can seal final ledger evidence during staging. The +transaction then compares the final ledger to the captured preimage and skips +construction when they match. An equivalent ledger retains its bytes and inode. +A no-change apply returns receipts without an object-store barrier or transaction. Commit outcome tracking is bound to the combined journal's UUID. Recovering a separate cache publication cannot claim that the combined generation committed. @@ -806,15 +834,15 @@ death the next writer recovers and raises `CoreError.transactionRecovered`; consumers retry the whole preparation. Previews reject pending recovery without replay. See [Updates](Updates.md) for the public handle and error contracts. -Pruning participates in that transaction. Pins referenced by skills, instruction -sections or prompt sections remain cached, as do artifact contents referenced by -watch state and trees containing live edit sources. Pruning opens directory -ancestry without following symlinks and uses directory-relative enumeration, -rename and deletion. It rejects symlinked cache containers and never recursively -follows a link during deletion. Mirrors remain available for source history and -future resolution. Watch-owned Git refs retain only revisions still referenced -by watch state or installed pins; obsolete histories can be collected by Git -after those refs are released. +Git object retention and materialized paths follow separate ledger edges. +Watch baselines and empty groups retain objects without creating pin +directories. Legacy self-contained Antigravity inputs retain their recorded +Git provenance and protect existing refs while replaying from the embedded +bytes. New Antigravity freezes use the same coordinate-only Git records as +other instruction targets. Filtered updates preserve an equivalent legacy +ledger when its rendered contributions and the selected state are unchanged. +The pending reference marker includes both deployed and pending generations +until recovery has selected a consistent ledger. Both doctors inspect cached objects, local Git refs or remote ref advertisements without fetching or populating caches. Local Git status disables optional locks @@ -823,6 +851,9 @@ to avoid index refresh writes. Skill doctor reports pending recovery as a transaction uses `unresolved-transaction` and lists retained recovery locations. It also reports missing installs, changed content and broken links, newer matching Git resolutions and uncommitted changes in selected local source paths. +Instruction doctor verifies each locked input, including nested includes and +prompt inputs, separately from deployed output drift. Each ordinary target +uses its own input health to decide whether to inspect Markdown links. `install` restores all recorded recipients and modes without changing lock bytes. The consuming CLI controls presentation and user interaction. diff --git a/Sources/AgentsCore/AcquisitionCache/GitAcquisition.swift b/Sources/AgentsCore/AcquisitionCache/GitAcquisition.swift index c9f9035..41e1690 100644 --- a/Sources/AgentsCore/AcquisitionCache/GitAcquisition.swift +++ b/Sources/AgentsCore/AcquisitionCache/GitAcquisition.swift @@ -280,7 +280,12 @@ struct GitAcquisition { let root = repository.deletingLastPathComponent() // Scope paths may carry ordinary config. Run init from a clean external workspace. try workspace { clean in - _ = try initialize(named: repository.path, in: clean, object: object) + let format = object.utf8.count == 64 ? "sha256" : "sha1" + _ = try git( + [ + "init", "--bare", "--template=", "--initial-branch=unborn", "--object-format=" + format, + repository.path, + ], in: clean, .extractRevision) _ = try git( ["-C", repository.path, "config", "remote.origin.url", url], in: clean, .readOrigin) _ = try git( @@ -292,23 +297,11 @@ struct GitAcquisition { try DirectoryHandle(at: root).sync() } - func archive(_ revision: String, repository: URL, to archive: URL) throws { - try workspace { root in - _ = try git( - ["-C", repository.path, "archive", "--format=tar", "--output=" + archive.path, revision], - in: root, .extractRevision) - } - } - - private func initialize(named name: String = "repository", in root: URL, object: String) throws - -> URL - { + private func initialize(in root: URL, object: String) throws -> URL { let format = object.utf8.count == 64 ? "sha256" : "sha1" - _ = try git( - ["init", "--bare", "--template=", "--object-format=" + format, name], in: root, .clone) - return URL( - fileURLWithPath: name, relativeTo: URL(fileURLWithPath: root.path, isDirectory: true) - ).standardizedFileURL + let repository = root.appendingPathComponent("repository", isDirectory: true) + try GitObjectDirectory.initializeBare(at: repository, format: format) + return repository } private func workspace(_ body: (URL) throws -> T) throws -> T { diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 36f928b..775e622 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -161,11 +161,12 @@ package final class DirectoryHandle { func remove( _ name: String, expecting expected: FileSnapshot? = nil, identity expectedIdentity: FileObjectIdentity? = nil, + streamingChildren: [String: FileObjectIdentity] = [:], checkpoint: (RemovalPoint) throws -> Void = { _ in } ) throws { try removeContents( name, expected: expected, identity: expectedIdentity, prefix: "", - checkpoint: checkpoint) + streamingChildren: streamingChildren, checkpoint: checkpoint) // An absent entry may be an interrupted unlink whose parent was not synced. try sync() try checkpoint(RemovalPoint(path: "", step: .synced)) @@ -173,6 +174,7 @@ package final class DirectoryHandle { private func removeContents( _ name: String, expected: FileSnapshot?, identity: FileObjectIdentity?, prefix: String, + streaming: Bool = false, streamingChildren: [String: FileObjectIdentity] = [:], checkpoint: (RemovalPoint) throws -> Void ) throws { guard let info = try info(name) else { return } @@ -184,9 +186,13 @@ package final class DirectoryHandle { throw CoreError.invalidState("removal ownership changed: \(name)") } if info.st_mode & S_IFMT == S_IFDIR { - let directory = try child(name) + let directory = try child(name, matching: info) + let mode = info.st_mode & 0o7777 + if let expected, !expected.permitsDisposalMode(mode) { + throw CoreError.invalidState("removal directory mode changed: \(name)") + } if info.st_mode & S_IRWXU != S_IRWXU { - guard fchmod(directory.descriptor, (info.st_mode & 0o7777) | S_IRWXU) == 0 else { + guard fchmod(directory.descriptor, (expected?.mode ?? mode) | S_IRWXU) == 0 else { throw CoreError.unsafePath("cannot make removed directory writable: \(name)") } } @@ -199,13 +205,25 @@ package final class DirectoryHandle { } try directory.removeContents( child, expected: recorded?[Data(child.utf8)], identity: nil, - prefix: prefix.isEmpty ? child : prefix + "/" + child, checkpoint: checkpoint) + prefix: prefix.isEmpty ? child : prefix + "/" + child, + streaming: streaming + || (streamingChildren[child] != nil + && streamingChildren[child] == recorded?[Data(child.utf8)]?.identity), + checkpoint: checkpoint) } try directory.sync() - } else if let expected, try FileSnapshot.read(name, from: self) != expected { + } else if let expected, + try FileSnapshot.read(name, from: self, streaming: streaming ? observed : nil) != expected + { throw CoreError.invalidState("removal content changed: \(name)") } - guard try self.info(name).map(FileObjectIdentity.init) == observed else { + guard let final = try self.info(name), FileObjectIdentity(final) == observed, + expected.map({ + observed.isDirectory + ? $0.permitsDisposalMode(final.st_mode & 0o7777) + : final.st_mode & 0o7777 == $0.mode + }) ?? true + else { throw CoreError.invalidState("removal identity changed: \(name)") } guard unlinkat(descriptor, name, info.st_mode & S_IFMT == S_IFDIR ? AT_REMOVEDIR : 0) == 0 @@ -363,8 +381,9 @@ package final class DirectoryHandle { a, data: Data("a".utf8), syncParent: false, afterCreate: { try checkpoint(.firstCreated) }) try write( b, data: Data("b".utf8), syncParent: false, afterCreate: { try checkpoint(.secondCreated) }) - let first = try info(a).map(FileObjectIdentity.init) - let second = try info(b).map(FileObjectIdentity.init) + guard let first = try info(a).map(FileObjectIdentity.init), + let second = try info(b).map(FileObjectIdentity.init) + else { throw CoreError.invalidState("atomic rename probe disappeared") } // Exchange must preserve both entries and exchange their physical identities. try atomicRename(a, to: self, named: b, mode: .exchange).requireSuccess("exchange atomic probe") try checkpoint(.exchanged) @@ -396,6 +415,9 @@ package final class DirectoryHandle { throw CoreError.unsupported("exclusive rename did not move the probe object") } try checkpoint(.verified) + // Staging synchronizes this container before publishing its ready entry. + try removeContents(b, expected: nil, identity: first, prefix: b, checkpoint: { _ in }) + try removeContents(c, expected: nil, identity: second, prefix: c, checkpoint: { _ in }) } @discardableResult @@ -593,8 +615,10 @@ package final class DirectoryHandle { /// Syncs a verified object's file contents, then each directory level after its children, /// then this parent. - func synchronize(_ name: String, as snapshot: FileSnapshot) throws { - guard try FileSnapshot.read(name, from: self) == snapshot else { + func synchronize( + _ name: String, as snapshot: FileSnapshot, streaming: FileObjectIdentity? = nil + ) throws { + guard try FileSnapshot.read(name, from: self, streaming: streaming) == snapshot else { throw CoreError.invalidState("transaction preimage changed before synchronization: \(name)") } try synchronizeContents(name, as: snapshot) @@ -602,14 +626,23 @@ package final class DirectoryHandle { } private func synchronizeContents(_ name: String, as snapshot: FileSnapshot) throws { + guard let before = try info(name), FileObjectIdentity(before) == snapshot.identity, + before.st_mode & 0o7777 == snapshot.mode + else { throw CoreError.invalidState("transaction preimage changed before sync: " + name) } if let children = snapshot.children { - let directory = try child(name) + let directory = try child(name, matching: before) for member in children { try directory.synchronizeContents(member.name, as: member.snapshot) } try directory.sync() } else if snapshot.isRegular { - try syncFile(name, includingParent: false) + let file = try regularFile(name) + defer { close(file) } + var opened = stat() + guard fstat(file, &opened) == 0, Self.sameGeneration(before, opened) else { + throw CoreError.invalidState("transaction file changed before sync: " + name) + } + try Self.synchronize(file) } } @@ -654,7 +687,7 @@ package final class DirectoryHandle { /// Copies through pinned descriptors, including modes, ACLs and extended attributes. func copy( _ name: String, from source: DirectoryHandle, named original: String, - prefix: String = "", syncParent: Bool = true, + prefix: String = "", syncParent: Bool = true, durable: Bool = true, checkpoint: (CopyPoint) throws -> Void = { _ in } ) throws { let path = prefix.isEmpty ? name : prefix + "/" + name @@ -674,17 +707,20 @@ package final class DirectoryHandle { R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) try checkpoint(CopyPoint(path: path, step: .directoryCreated)) let destination = try child(name) - let origin = try source.child(original) + let origin = try source.child(original, matching: info) for entry in try origin.names() { try destination.copy( - entry, from: origin, named: entry, prefix: path, syncParent: false, checkpoint: checkpoint + entry, from: origin, named: entry, prefix: path, syncParent: false, durable: durable, + checkpoint: checkpoint ) } - try Self.copyMetadata(from: origin.descriptor, to: destination.descriptor, mode: info.st_mode) + try Self.copyMetadata( + from: origin.descriptor, to: destination.descriptor, mode: info.st_mode, durable: durable) case S_IFLNK: try link(name, destination: source.readLink(original), syncParent: false) try checkpoint(CopyPoint(path: path, step: .linkCreated)) - guard platform_copy_link_metadata(source.descriptor, original, descriptor, name) == 0 else { + guard platform_copy_link_metadata(source.descriptor, original, descriptor, name, durable) == 0 + else { throw CoreError.invalidState("cannot preserve link metadata: \(errno)") } case S_IFREG: @@ -707,18 +743,20 @@ package final class DirectoryHandle { guard platform_copy_data(origin, destination) == 0 else { throw CoreError.invalidState("cannot copy file content") } - try Self.copyMetadata(from: origin, to: destination, mode: info.st_mode) + try Self.copyMetadata(from: origin, to: destination, mode: info.st_mode, durable: durable) default: throw CoreError.unsafePath("unsupported filesystem entry: \(original)") } - if syncParent { try sync() } + if durable && syncParent { try sync() } if !prefix.isEmpty { try checkpoint(CopyPoint(path: path, step: .entryCopied)) } } - private static func copyMetadata(from origin: Int32, to destination: Int32, mode: mode_t) throws { - guard platform_copy_metadata(origin, destination, mode) == 0 else { + private static func copyMetadata( + from origin: Int32, to destination: Int32, mode: mode_t, durable: Bool = true + ) throws { + guard platform_copy_metadata(origin, destination, mode, durable) == 0 else { throw CoreError.invalidState("cannot preserve filesystem metadata: \(errno)") } - synchronizationObserver?.didSynchronize() + if durable { synchronizationObserver?.didSynchronize() } } } diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index ef817b2..ea964d4 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -33,7 +33,10 @@ package final class FileTransaction { let security: TransactionSecurity let privateData: (() throws -> PrivateMaterializationResult)? var privateTree: PrivateTree? = nil - var installs: Bool { source != nil || security.replacement == .privateMaterialization } + var deferredLedger: (() throws -> Data?)? = nil + var installs: Bool { + source != nil || deferredLedger != nil || security.replacement == .privateMaterialization + } } private let store: StateStore private let checkpoint: (String) throws -> Void @@ -376,6 +379,18 @@ package final class FileTransaction { unchanged += evidence } + /// Private native staging can determine the final lock evidence without exposing bindings. + package func stageResolvedLedger( + expecting original: TargetPrecondition, producing replacement: @escaping () throws -> Data? + ) throws { + let (path, evidence, security) = try request(store.resolvedURL, expecting: original) + guard !security.isPrivate else { throw CoreError.invalidState("invalid ledger access") } + requests.append( + .init( + path: path, evidence: evidence, source: nil, expectation: .init(), security: security, + privateData: nil, deferredLedger: replacement)) + } + private func validateUnchanged() throws { for evidence in unchanged { try evidence.validate(excludingTargets: targetPaths) } } @@ -401,7 +416,11 @@ package final class FileTransaction { guard !requests.contains(where: { $0.path == path }) else { throw CoreError.invalidState("duplicate transaction destination") } - let evidence = try expecting ?? TargetPrecondition(destination) + let evidence = + try expecting + ?? (TransactionPaths.isMaterializedPin(path) + ? TargetPrecondition(materializedPin: destination, store: store) + : TargetPrecondition(destination)) if let route = NativeTargetRoute.targetRoute(path), let snapshot = evidence.snapshot { let requiredKind: mode_t = route.isContainer ? S_IFDIR : S_IFREG guard snapshot.identity.kind == requiredKind else { @@ -472,6 +491,10 @@ package final class FileTransaction { } package func commit() throws { + try commit(journalAdmissionLimits: .standard) + } + + func commit(journalAdmissionLimits: LedgerLimits) throws { guard !requests.isEmpty else { return } for request in requests where request.security.replacement == .privateMaterialization { try store.excludeHostCommands( @@ -524,7 +547,18 @@ package final class FileTransaction { try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() } for (index, request) in requests.enumerated() { - if let state = receiptIndices[index] { + session.preimageSizes[index] = request.evidence.size + if let replacement = request.deferredLedger { + if let bytes = try replacement() { + try session.stage(index, source: .data(bytes), expectation: request.expectation) + } else { + guard request.evidence.snapshot?.isRegular == true else { + throw CoreError.invalidState("missing deferred ledger preimage") + } + try session.requirePreimage(index) + try session.advance(index, to: .skipped) + } + } else if let state = receiptIndices[index] { try session.stage(index, source: request.source, expectation: request.expectation) { let bytes = try StateStore.encode( session.materializationReceipts( @@ -545,6 +579,7 @@ package final class FileTransaction { try session.emit(.preconditions) try validateUnchanged() try session.validatePreimages() + try session.admitDisposal(journalLimits: journalAdmissionLimits) outcome.requireRecovery() for index in session.journal.entries.indices { try session.publish(index) } try validateUnchanged() @@ -553,7 +588,7 @@ package final class FileTransaction { try session.finish(.committed) outcome.recordTerminal(.committed) try session.emit(.phase(.committed)) - try session.dispose() + try session.dispose(checkingComplete: true) outcome.recoveryPending = false } catch { // Recovery names its checkpoints under `recovery.`, apart from the failed commit's. diff --git a/Sources/AgentsCore/GitTarSelection.swift b/Sources/AgentsCore/GitTarSelection.swift new file mode 100644 index 0000000..98cc481 --- /dev/null +++ b/Sources/AgentsCore/GitTarSelection.swift @@ -0,0 +1,139 @@ +import Foundation + +/// Filters Git's ustar/PAX stream in bounded chunks before handing it to tar. +enum GitTarSelection { + private struct Attributes { + var path: Data? + var size: Int? + } + + static func copy( + from input: FileHandle, to destination: URL, keeping paths: Set + ) throws -> Set { + try Data().write(to: destination) + let output = try FileHandle(forWritingTo: destination) + defer { try? output.close() } + var kept = Set() + var extended = Data() + var global = Attributes() + var local = Attributes() + let bufferSize = 65_536 + var incoming = Data() + var offset = 0 + var outgoing = Data() + func invalid() -> CoreError { .invalidSource("invalid Git tar stream") } + func read(_ size: Int) throws -> Data { + while incoming.count - offset < size { + guard let chunk = try input.read(upToCount: bufferSize), !chunk.isEmpty else { + throw invalid() + } + if offset > 0 { + incoming.removeSubrange(0..= bufferSize { + try output.write(contentsOf: outgoing) + outgoing.removeAll(keepingCapacity: true) + if bytes.count >= bufferSize { + try output.write(contentsOf: bytes) + return + } + } + outgoing.append(bytes) + } + func octal(_ bytes: Data) -> Int? { + let number = bytes.drop(while: { $0 == 32 || $0 == 0 }).prefix(while: { $0 != 32 && $0 != 0 }) + return number.isEmpty ? 0 : Int(String(decoding: number, as: UTF8.self), radix: 8) + } + func padding(for size: Int?) throws -> Int { + guard let size, size >= 0, size <= Int.max - 511 else { throw invalid() } + return (size + 511) / 512 * 512 + } + func apply(_ bytes: Data.SubSequence, to attributes: inout Attributes) throws { + var bytes = bytes + while !bytes.isEmpty { + guard let space = bytes.firstIndex(of: 32), + let count = Int(String(decoding: bytes[.. space - bytes.startIndex + 1, count <= bytes.count + else { throw invalid() } + let record = bytes.prefix(count).dropFirst(space - bytes.startIndex + 1) + guard record.last == 10 else { throw invalid() } + if record.starts(with: "path=".utf8) { + let path = Data(record.dropFirst(5).dropLast()) + attributes.path = path.isEmpty ? nil : path + } else if record.starts(with: "size=".utf8) { + let size = record.dropFirst(5).dropLast() + if size.isEmpty { + attributes.size = nil + } else { + guard size.allSatisfy({ (48...57).contains($0) }), + let value = Int(String(decoding: size, as: UTF8.self)) + else { throw invalid() } + attributes.size = value + } + } + bytes = bytes.dropFirst(count) + } + } + while true { + try Task.checkCancellation() + let header = try read(512) + if header.allSatisfy({ $0 == 0 }) { + guard extended.isEmpty else { throw invalid() } + try write(Data(count: 1024)) + try output.write(contentsOf: outgoing) + return kept + } + let type = header[156] + if type == 120 || type == 103 { + guard let size = octal(header[124..<136]) else { throw invalid() } + let padded = try padding(for: size) + guard padded <= 1024 * 1024, extended.isEmpty else { throw invalid() } + let data = try read(padded) + let attributes = data.prefix(size) + if type == 103 { + try apply(attributes, to: &global) + try write(header) + try write(data) + } else { + extended = header + data + local = global + try apply(attributes, to: &local) + } + continue + } + guard [0, 48, 50, 53].contains(type) else { throw invalid() } + let attributes = extended.isEmpty ? global : local + let name = header.prefix(100).prefix(while: { $0 != 0 }) + let prefix = header[345..<500].prefix(while: { $0 != 0 }) + var path = attributes.path ?? (prefix.isEmpty ? Data(name) : Data(prefix) + Data([47]) + name) + while path.last == 47 { path.removeLast() } + let include = paths.contains(path) + if include { + guard kept.insert(path).inserted else { throw invalid() } + try write(extended) + try write(header) + } + extended = Data() + var remaining = try padding(for: attributes.size ?? octal(header[124..<136])) + while remaining > 0 { + let count = min(remaining, bufferSize) + let data = try read(count) + if include { try write(data) } + remaining -= count + } + } + } +} diff --git a/Sources/AgentsCore/GitTreeArchive.swift b/Sources/AgentsCore/GitTreeArchive.swift new file mode 100644 index 0000000..83786dc --- /dev/null +++ b/Sources/AgentsCore/GitTreeArchive.swift @@ -0,0 +1,624 @@ +import Foundation + +package struct UnverifiableGitArchive: Error, CustomStringConvertible { + let revision: String + let path: String + + package var description: String { "Unverifiable Git archive at \(revision)/\(path)" } +} + +/// A Git object's storage coordinates are independent of a worktree's HEAD and configuration. +struct GitObjectDirectory { + let git: URL + let objects: URL + let format: String + + init(repository: URL, source: String? = nil, lock: Int32? = nil) throws { + func coordinates(_ fields: [String]) throws -> String { + let args = ["--no-optional-locks", "rev-parse", "--path-format=absolute"] + fields + let output = try ProcessRunner.isolatedGit(args, in: repository, inheritingLock: lock) + guard output.exitCode == 0, output.validUTF8, output.stdout.utf8.last == 10 else { + throw gitFailure( + args, output, source: source ?? repository.path, operation: .findRepositoryRoot, + replacingPaths: [repository]) + } + // Remove only the record terminator. Paths can themselves end in a newline. + return String(decoding: output.stdout.utf8.dropLast(), as: UTF8.self) + } + let combined = try coordinates(["--git-dir", "--git-common-dir", "--show-object-format"]) + var values = combined.utf8.split(separator: 10, omittingEmptySubsequences: false).map { + String(decoding: $0, as: UTF8.self) + } + if values.count > 3, let format = values.last { + values = try [coordinates(["--git-dir"]), coordinates(["--git-common-dir"]), format] + } + guard values.count == 3, values[0].hasPrefix("/"), values[1].hasPrefix("/"), + ["sha1", "sha256"].contains(values[2]) + else { throw CoreError.invalidState("invalid Git object directory coordinates") } + git = URL(fileURLWithPath: values[0], isDirectory: true) + objects = URL(fileURLWithPath: values[1], isDirectory: true).appendingPathComponent("objects") + format = values[2] + } + + static func initializeBare(at repository: URL, format: String) throws { + let manager = FileManager.default + for path in ["objects/info", "objects/pack", "refs/heads", "refs/tags"] { + try manager.createDirectory( + at: repository.appendingPathComponent(path), withIntermediateDirectories: true) + } + try Data("ref: refs/heads/unborn\n".utf8).write(to: repository.appendingPathComponent("HEAD")) + let sha256 = format == "sha256" + let config = repository.appendingPathComponent("config") + try Data().write(to: config) + var contents = "[core]\n\trepositoryformatversion = \(sha256 ? 1 : 0)\n\tbare = true\n" + var info = stat() + if lstat(repository.appendingPathComponent("CoNfIg").path, &info) == 0 { + contents += "\tignorecase = true\n" + } + #if os(macOS) + // Git precomposes command-line paths on volumes with decomposing name lookup. + let composed = repository.appendingPathComponent(".probe-\u{00fc}") + try Data().write(to: composed) + let decomposed = repository.appendingPathComponent(".probe-u\u{0308}") + let precomposes = lstat(decomposed.path, &info) == 0 + try manager.removeItem(at: composed) + contents += "\tprecomposeunicode = \(precomposes)\n" + #endif + if sha256 { contents += "[extensions]\n\tobjectformat = sha256\n" } + try Data(contents.utf8).write(to: config) + } + + func borrow(in workspace: URL, named name: String) throws -> URL { + let repository = workspace.appendingPathComponent(name, isDirectory: true) + try Self.initializeBare(at: repository, format: format) + // Quote the alternate as a Git pathname so its raw bytes occupy one line. + let quoted = objects.path.utf8.map { byte -> String in + if byte == 34 || byte == 92 || byte < 32 || byte >= 127 { + return String(format: "\\%03o", byte) + } + return String(UnicodeScalar(byte)) + }.joined() + try Data(("\"" + quoted + "\"\n").utf8).write( + to: repository.appendingPathComponent("objects/info/alternates")) + return repository + } +} + +private func gitFailure( + _ arguments: [String], _ output: ProcessOutput, source: String, + operation: GitError.Operation = .extractRevision, replacingPaths: [URL] = [] +) -> GitError { + GitError( + operation: operation, source: source, stderr: output.stderr, command: ["git"] + arguments, + exitCode: output.exitCode, replacingPaths: replacingPaths) +} + +struct GitTreeArchive { + /// A structural request visits the entry and its ancestry without selecting its children. + struct Selection: Hashable { + let path: String + var recursive = true + var followsLinks = true + var optional = false + + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.path.utf8.elementsEqual(rhs.path.utf8) && lhs.recursive == rhs.recursive + && lhs.followsLinks == rhs.followsLinks && lhs.optional == rhs.optional + } + + func hash(into hasher: inout Hasher) { + hasher.combine(Data(path.utf8)) + hasher.combine(recursive) + hasher.combine(followsLinks) + hasher.combine(optional) + } + } + + struct Coverage { + var entries: Set = [] + var links: Set = [] + var gitlinks: Set = [] + var omittedDirectories: Set = [] + var optionalSelections: [Selection: SourceSnapshot.Lookup] = [:] + } + + private struct Entry { + let mode: Substring + let type: Substring + let oid: String + let path: Data + + var isDirectory: Bool { mode == "040000" } + var isLink: Bool { mode == "120000" } + var isGitlink: Bool { mode == "160000" } + } + + let repository: URL + let workspace: URL + let revision: String + let source: String + let lock: Int32? + var historical = false + var committedAttributesOnly = false + + struct MissingCommit: Error, CustomStringConvertible { + let revision: String + var description: String { "missing Git commit " + revision } + } + + private func git(_ args: [String], input: Data? = nil, in directory: URL? = nil) throws -> String + { + try Task.checkCancellation() + let file = workspace.appendingPathComponent("input") + if let input { try input.write(to: file) } + let handle = try input.map { _ in try FileHandle(forReadingFrom: file) } + defer { try? handle?.close() } + let output = try ProcessRunner.isolatedGit( + args, in: directory ?? repository, inheritingLock: lock, input: handle) + guard output.exitCode == 0 else { + throw gitFailure(args, output, source: source, replacingPaths: [repository, workspace]) + } + guard output.validUTF8 else { + throw CoreError.invalidSource("invalid UTF-8 Git data at " + revision) + } + return output.stdout + } + + private func readTree(_ tree: String, recursively: Bool = false) throws -> [Entry] { + let args = ["ls-tree", "-z"] + (recursively ? ["-r", "-t"] : []) + [tree] + var bytes = Data() + let output = try ProcessRunner.isolatedGit( + args, in: repository, inheritingLock: lock, + output: { bytes = try $0.readToEnd() ?? Data() }) + guard output.exitCode == 0 else { + throw gitFailure(args, output, source: source, replacingPaths: [repository, workspace]) + } + guard bytes.isEmpty || bytes.last == 0 else { throw integrity(".", "invalid tree record") } + return try bytes.split(separator: 0).map { record in + guard let tab = record.firstIndex(of: 9) else { throw integrity(".", "invalid tree record") } + let header = String(decoding: record[.. CoreError { + .invalidState("Git commit \(revision) at \(path): \(message)") + } + + private func checkObjects(_ objects: [String: String]) throws { + guard !objects.isEmpty else { return } + let ids = objects.keys.sorted() + let output = try git( + ["cat-file", "--batch-check=%(objectname) %(objecttype)"], + input: Data((ids.joined(separator: "\n") + "\n").utf8)) + let records = output.split(separator: "\n") + guard records.count == ids.count else { throw integrity(".", "invalid Git object evidence") } + for (id, record) in zip(ids, records) { + if id == revision && record == "\(id) missing" { throw MissingCommit(revision: revision) } + guard record == "\(id) \(objects[id]!)" else { + if id == revision { + throw CoreError.invalidState("Git selection is not a commit: " + revision) + } + throw integrity(".", "missing or invalid object " + id) + } + } + } + + /// Resolve path components in filesystem order and export the corresponding archive entries. + /// Optional selections are absent only after a successful lookup in the parent tree. + func extract( + _ requested: [Selection], into destination: URL, uncoveredSupport: Set = [], + observingCoverage: ((Coverage) -> Void)? = nil + ) throws { + guard SourceCache.isObjectID(revision) else { + throw CoreError.invalidState("expected exact Git commit") + } + try Task.checkCancellation() + let root: String + do { + root = try git(["rev-parse", "--verify", revision + "^{tree}"]) + .trimmingCharacters(in: .newlines) + guard SourceCache.isObjectID(root) else { throw integrity(".", "invalid root tree") } + } catch { + // Only a missing exact commit allows the caller to consult another object store. + try checkObjects([revision: "commit"]) + throw error + } + + let attributesPath = Data(".gitattributes".utf8) + var hasAttributes = !committedAttributesOnly + var listings: [String: [Data: Entry]] = [:] + func listing(_ tree: String) throws -> [Data: Entry] { + if let cached = listings[tree] { return cached } + var entries: [Data: Entry] = [:] + for entry in try readTree(tree) { + guard entries.updateValue(entry, forKey: entry.path) == nil else { + throw integrity(".", "ambiguous tree entry") + } + } + if entries[attributesPath] != nil { hasAttributes = true } + listings[tree] = entries + return entries + } + var found: [Data: Entry] = [:] + var directories: [Data: String] = [:] + var pathspecs: [Data: String] = [:] + var expanded: Set = [] + var selectedEntries: Set = [] + var optionalPaths: [Selection: (traversed: Set, throughLinkEntry: Set?)] = [:] + var links: [String: String] = [:] + var requiredObjects = [revision: "commit"] + guard root != revision else { + try checkObjects(requiredObjects) + throw integrity(".", "commit cannot be its own tree") + } + requiredObjects[root] = "tree" + func select(_ entry: Entry) throws { + guard ["040000", "100644", "100755", "120000", "160000"].contains(entry.mode), + let path = String(data: entry.path, encoding: .utf8) + else { throw integrity(".", "unsupported tree entry") } + try ledgerPath(path) + found[entry.path] = entry + if !entry.isGitlink { + let type = String(entry.type) + guard requiredObjects[entry.oid].map({ $0 == type }) ?? true else { + throw integrity(path, "conflicting tree object type") + } + requiredObjects[entry.oid] = type + } + } + + func resolve(_ request: Selection, nestedLink: Bool = false) throws { + enum Step { + case part(String) + case finishLink + } + func steps(_ path: String) -> [Step] { + path.utf8.split(separator: 47).reversed().map { + .part(String(decoding: $0, as: UTF8.self)) + } + } + try ledgerPath(request.path) + var pending = steps(request.path) + var parents: [(name: String, tree: String)] = [] + var hops = 0 + var activeLinks = 0 + var filePath: String? + let observingSelection = request.optional && observingCoverage != nil + var traversed = Set() + var throughLinkEntry: Set? + while let step = pending.popLast() { + guard case .part(let name) = step else { + activeLinks -= 1 + continue + } + if let filePath { throw integrity(filePath, "path traverses a non-directory") } + if name == "." { continue } + if name == ".." { + guard !parents.isEmpty else { + throw CoreError.unsafePath("Git link escapes " + request.path) + } + parents.removeLast() + continue + } + let path = (parents.map(\.name) + [name]).joined(separator: "/") + let key = Data(path.utf8) + guard let child = try listing(parents.last?.tree ?? root)[Data(name.utf8)] else { + if (request.optional && activeLinks == 0) || nestedLink { return } + throw integrity(request.path, "missing locked path at " + path) + } + let entry = Entry(mode: child.mode, type: child.type, oid: child.oid, path: key) + try select(entry) + if observingSelection { traversed.insert(key) } + if entry.isLink { + guard request.followsLinks else { + throw CoreError.unsafePath("Git input is a link: " + path) + } + // Capture the exact requested entry before descending into its link target. + if observingSelection && pending.isEmpty { throughLinkEntry = traversed } + hops += 1 + guard hops <= 32 else { throw CoreError.unsafePath("Git link cycle at " + request.path) } + pathspecs[key] = path + let link = try links[entry.oid] ?? git(["cat-file", "blob", entry.oid]) + links[entry.oid] = link + guard !link.isEmpty, !link.hasPrefix("/"), !link.contains("\0") else { + throw CoreError.unsafePath("invalid Git link at " + path) + } + activeLinks += 1 + pending.append(.finishLink) + if link.utf8.last == 47 { pending.append(.part(".")) } + pending += steps(link) + continue + } + if entry.isDirectory { + directories[key] = path + parents.append((name, entry.oid)) + } else { + pathspecs[key] = path + filePath = path + } + } + if observingSelection { optionalPaths[request] = (traversed, throughLinkEntry) } + guard filePath == nil, request.recursive else { return } + let prefix = parents.map(\.name).joined(separator: "/") + let key = Data(prefix.utf8) + if expanded.contains(where: { $0.isEmpty || $0 == key || key.starts(with: $0 + Data([47])) }) + { + return + } + expanded.insert(key) + pathspecs[key] = prefix.isEmpty ? "." : prefix + let descendants = prefix.isEmpty ? Data() : key + Data([47]) + for child in try readTree(parents.last?.tree ?? root, recursively: true) { + if child.path.split(separator: 47).last?.elementsEqual(attributesPath) == true { + hasAttributes = true + } + let entry = Entry( + mode: child.mode, type: child.type, oid: child.oid, path: descendants + child.path) + selectedEntries.insert(entry.path) + try select(entry) + let path = String(decoding: entry.path, as: UTF8.self) + if entry.isDirectory { + directories[entry.path] = path + } else if entry.isLink { + // Nested links are checked even when the request rejects links on its own path. + try resolve(.init(path: path), nestedLink: true) + } + } + } + do { + for request in requested { try resolve(request) } + } catch { + try checkObjects([revision: "commit"]) + throw error + } + try checkObjects(requiredObjects) + func coverage(for entries: Set) -> Coverage { + Coverage( + entries: entries, links: Set(found.values.lazy.filter(\.isLink).map(\.path)), + gitlinks: Set(found.values.lazy.filter(\.isGitlink).map(\.path)), + omittedDirectories: Set(directories.keys.lazy.filter { !entries.contains($0) }), + optionalSelections: optionalPaths.mapValues { paths in + if paths.traversed.isSubset(of: entries) { return .available } + if paths.throughLinkEntry?.isSubset(of: entries) == true { return .omittedTarget } + return .spellingMiss + }) + } + try FileSystem.createDirectory(at: destination) + guard !pathspecs.isEmpty else { + try createDirectories(directories.values, in: destination) + observingCoverage?(coverage(for: Set(directories.keys))) + return + } + let stateful = + try hasAttributes + && usesStatefulSubstitution( + found.values.filter { $0.type == "blob" && !$0.isLink }.sorted { + $0.path.lexicographicallyPrecedes($1.path) + }, + uncoveredSupport: uncoveredSupport) + let args = ["--literal-pathspecs", "archive", "--format=tar", revision] + let selection = + historical || stateful || expanded.contains(Data()) + ? [] : ["--"] + pathspecs.sorted { $0.key.lexicographicallyPrecedes($1.key) }.map(\.value) + let filtered = workspace.appendingPathComponent("selected.tar") + var archived = Set() + let archiveArguments = args + selection + let paths = Set(found.keys).union(directories.keys) + func filter(_ stream: FileHandle) throws { + archived = try GitTarSelection.copy(from: stream, to: filtered, keeping: paths) + } + var archiveRepository = repository + var output = try ProcessRunner.isolatedGit( + archiveArguments, in: archiveRepository, inheritingLock: lock, output: filter) + if output.exitCode != 0, committedAttributesOnly, !selection.isEmpty { + // Git's pathspec validation may visit trees outside the requested closure. Retry + // with only verified paths and their committed attributes visible to the archiver. + archiveRepository = try scopedArchiveRepository( + root: root, expanded: expanded, entries: found.values, + attribute: attributesPath, listing: listing) + output = try ProcessRunner.archiveScopedGitTree( + archiveArguments, in: archiveRepository, inheritingLock: lock, output: filter) + } + guard output.exitCode == 0 else { + throw gitFailure( + archiveArguments, output, source: source, replacingPaths: [archiveRepository, workspace]) + } + try ProcessRunner.unpackGitArchive(filtered, into: destination) + let structural = directories.filter { + !archived.contains($0.key) && !selectedEntries.contains($0.key) + } + try createDirectories(structural.values, in: destination) + // Compare spellings reported by the filesystem, including directories implicitly made by tar. + var expected = Set(archived.union(structural.keys)) + for path in Array(expected) { + let parts = path.split(separator: 47) + for count in 1.., entries: some Sequence, attribute: Data, + listing: (String) throws -> [Data: Entry] + ) throws -> URL { + let objects = try GitObjectDirectory(repository: repository, source: source, lock: lock) + let scoped = try objects.borrow(in: workspace, named: "scoped-archive") + var children: [Data: [Entry]] = [:] + for entry in entries { + let parent = entry.path.lastIndex(of: 47).map { Data(entry.path[..<$0]) } ?? Data() + children[parent, default: []].append(entry) + } + func writeTree(_ tree: String, at path: Data) throws -> String { + if expanded.contains(path) { return tree } + var records = Data() + func append(_ entry: Entry, name: Data, oid: String) { + records.append(contentsOf: "\(entry.mode) \(entry.type) \(oid)\t".utf8) + records.append(name) + records.append(0) + } + var selectedAttributes = false + for entry in children[path, default: []] { + let start = entry.path.lastIndex(of: 47).map { $0 + 1 } ?? entry.path.startIndex + let name = Data(entry.path[start...]) + let oid = try entry.isDirectory ? writeTree(entry.oid, at: entry.path) : entry.oid + append(entry, name: name, oid: oid) + selectedAttributes = selectedAttributes || name == attribute + } + if !selectedAttributes, let entry = try listing(tree)[attribute], + entry.mode == "100644" || entry.mode == "100755" + { + append(entry, name: attribute, oid: entry.oid) + } + let oid = try git(["mktree", "-z"], input: records, in: scoped) + .trimmingCharacters(in: .newlines) + guard SourceCache.isObjectID(oid) else { throw integrity(".", "invalid scoped tree") } + return oid + } + let scopedRoot = try writeTree(root, at: Data()) + // Replace only the root tree in this private namespace. Git still reads the exact + // original commit, including its author, dates and tree ID for export-subst. + let refs = scoped.appendingPathComponent("refs/replace") + try FileManager.default.createDirectory(at: refs, withIntermediateDirectories: false) + try Data((scopedRoot + "\n").utf8).write(to: refs.appendingPathComponent(root)) + return scoped + } + + private func createDirectories(_ directories: some Sequence, in root: URL) throws { + let base = try DirectoryHandle(at: root) + for path in directories.sorted() { + var parent = base + for part in path.utf8.split(separator: 47) { + let name = String(decoding: part, as: UTF8.self) + parent = try parent.directory(name) ?? parent.makeDirectory(name, syncParent: false) + } + } + } + + private func usesStatefulSubstitution(_ files: [Entry], uncoveredSupport: Set) throws + -> Bool + { + guard !files.isEmpty else { return false } + let input = Data(files.flatMap { Array($0.path) + [0] }) + let output = try git( + ["check-attr", "--source=" + revision, "-z", "--stdin", "export-subst"], input: input) + let fields = output.utf8.split(separator: 0).map { String(decoding: $0, as: UTF8.self) } + guard fields.count == files.count * 3 else { + throw integrity(".", "invalid archive attributes") + } + var stateful = false + for (index, file) in files.enumerated() where fields[index * 3 + 2] == "set" { + let path = String(decoding: file.path, as: UTF8.self) + let size = try git(["cat-file", "-s", file.oid]).trimmingCharacters(in: .newlines) + guard let bytes = Int(size), bytes >= 0, bytes <= LedgerLimits.standard.resourceBytes else { + throw UnverifiableGitArchive(revision: revision, path: path) + } + let args = ["cat-file", "blob", file.oid] + var blob = Data() + let result = try ProcessRunner.isolatedGit(args, in: repository, inheritingLock: lock) { + stream in + while let chunk = try stream.read(upToCount: 65_536), !chunk.isEmpty { + guard chunk.count <= bytes - blob.count else { + throw integrity(path, "archive blob grew during inspection") + } + blob.append(chunk) + } + } + guard result.exitCode == 0, blob.count == bytes else { + throw gitFailure(args, result, source: source, replacingPaths: [repository, workspace]) + } + let marker = Data("$Format:".utf8) + var start = blob.startIndex + while let prefix = blob.range(of: marker, in: start.. (Bool, Bool, Bool) { + var tokens = format[...] + var reproducible = true + var describe = false + var unstable = false + while let marker = tokens.firstIndex(of: 37) { + tokens = tokens[(marker + 1)...] + if tokens.first == 37 { + tokens = tokens.dropFirst() + continue + } + if let modifier = tokens.first, [32, 43, 45].contains(modifier) { + tokens = tokens.dropFirst() + if tokens.first == 37 { continue } + } + guard let token = tokens.popFirst() else { return (false, describe, unstable) } + switch token { + case 110, 72, 84, 80, 115, 102, 98, 66, 101: + // %n %H %T %P %s %f %b %B %e + break + case 120: // %xHH + let hex = tokens.prefix(2) + let valid = + hex.count == 2 + && hex.allSatisfy { + (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) + } + if valid { tokens = tokens.dropFirst(2) } + reproducible = reproducible && valid + case 97, 99: // %a and %c fields without mailmap or relative time + let field = tokens.first + unstable = unstable || field == 114 || field == 104 + let immutable = field.map { "netiIDs".utf8.contains($0) } ?? false + if immutable { tokens = tokens.dropFirst() } + reproducible = reproducible && immutable + default: + if token == 40, tokens.starts(with: "describe".utf8) { + let suffix = tokens.dropFirst("describe".utf8.count).first + describe = describe || suffix == 58 || suffix == 41 + } + unstable = unstable || [104, 116, 112].contains(token) + reproducible = false + } + } + return (reproducible, describe, unstable) + } +} diff --git a/Sources/AgentsCore/LedgerGitPin.swift b/Sources/AgentsCore/LedgerGitPin.swift new file mode 100644 index 0000000..ac13284 --- /dev/null +++ b/Sources/AgentsCore/LedgerGitPin.swift @@ -0,0 +1,218 @@ +import Foundation + +/// The repository-relative closure owned by the root authority, including contained sources. +package struct LedgerGitPin { + package let key: RetentionReferences.Git + package let source: SourceDeclaration + package let resources: [String: LedgerResource] + + package static func collect( + _ ledger: ResolvedLedger, roots: [String: URL], ids: Set? = nil + ) throws -> [RetentionReferences.Git: Self] { + var sources: [RetentionReferences.Git: SourceDeclaration] = [:] + var groups: [RetentionReferences.Git: [String: LedgerResource]] = [:] + for (id, resource) in ledger.resources + where resource.kind == .git && (ids?.contains(id) ?? true) { + var sourceID = resource.source + while let parent = ledger.sources[sourceID]?.container { sourceID = parent } + guard let source = ledger.sources[sourceID] else { + throw CoreError.invalidState("missing Git resource authority") + } + let identity = try ledger.sourceIdentity(sourceID, roots: roots) + let key = RetentionReferences.Git(source: identity, revision: source.revision) + if let transport = source.transport { + sources[key] = .init( + kind: .git, location: transport, requirement: .revision(source.revision)) + } else if let location = source.location { + sources[key] = try .init( + kind: .local, location: location.resolve(roots: roots).path, + requirement: .revision(source.revision)) + } else { + throw CoreError.invalidState("missing pinned source coordinates") + } + groups[key, default: [:]][id] = resource + } + return Dictionary( + uniqueKeysWithValues: groups.map { key, resources in + (key, Self(key: key, source: sources[key]!, resources: resources)) + }) + } + + var selection: [GitTreeArchive.Selection] { + var requests = Set() + for resource in resources.values { + requests.insert(.init(path: resource.path)) + for entry in resource.support { + requests.insert(.init(path: entry.path, recursive: false)) + } + } + return requests.sorted { ($0.path, $0.recursive ? 1 : 0) < ($1.path, $1.recursive ? 1 : 0) } + } + + var firstSupportFile: String? { + resources.values.flatMap(\.support).filter { $0.kind == .file }.map(\.path).sorted().first + } + + package var needsSupportAuthentication: Bool { firstSupportFile != nil } + + /// Directory hashes cover selected files and symlink spellings, excluding external support. + func uncoveredSupportPaths() throws -> Set { + var support = Set() + var covered = Set() + for resource in resources.values { + let coordinates = Set(resource.support.filter { $0.kind == .file }.map { Data($0.path.utf8) }) + support.formUnion(coordinates) + for entry in try LedgerResources.pinEntries(resource) where entry.kind == .file { + let path = Data(entry.path.utf8) + if !coordinates.contains(path) { covered.insert(path) } + } + } + return support.subtracting(covered) + } + + package func file(_ resource: LedgerResource, in root: URL) throws -> URL { + let file = try PathSafety.resolvedChild(base: root, subpath: resource.path) + let base = root.resolvingSymlinksInPath() + guard let physical = PathSafety.realPath(file.path), + PathSafety.isContained(URL(fileURLWithPath: physical), in: base) + else { throw invalid(resource.path, "locked resource is missing or escapes its pin") } + return file + } + + package func verify( + _ resource: LedgerResource, in root: URL, authenticatingSupportFrom canonical: URL?, + uncoveredSupport: Set? = nil + ) throws { + let file = try file(resource, in: root) + let captured = try LedgerResources.capture( + file, embed: false, limits: .standard, sourceRoot: root) + guard captured.hash == resource.hash, captured.entries == resource.entries, + captured.support == resource.support + else { throw invalid(resource.path, "locked resource content or execute bits changed") } + for entry in resource.support where entry.kind == .file { + if let uncoveredSupport, !uncoveredSupport.contains(Data(entry.path.utf8)) { continue } + guard let canonical else { throw invalid(entry.path, "unverifiable locked Git support") } + // Exact extraction admits contextual support only when a selected resource hashes its bytes. + if root == canonical { continue } + let actual = try PathSafety.resolvedChild(base: root, subpath: entry.path) + let expected = try PathSafety.resolvedChild(base: canonical, subpath: entry.path) + guard let expectedBytes = try TargetPrecondition.readingFile(expected).bytes else { + throw invalid(entry.path, "unverifiable locked Git support") + } + guard try TargetPrecondition.readingFile(actual).bytes == expectedBytes else { + throw invalid( + entry.path, "unverifiable locked Git support: bytes differ from the exact archive") + } + } + } + + private func invalid(_ path: String, _ reason: String) -> CoreError { + .invalidState("\(key.source) at \(key.revision)/\(path): \(reason)") + } + + /// Includes structural parents and physical paths reached through committed links. + private func entries() throws -> [Data: LedgerEntry] { + var result: [Data: LedgerEntry] = [:] + func append(_ entry: LedgerEntry) throws { + let bytes = Data(entry.path.utf8) + if let prior = result[bytes], prior != entry { + throw invalid(entry.path, "conflicting locked Git coordinates") + } + result[bytes] = entry + } + for resource in resources.values { + for entry in try LedgerResources.pinEntries(resource) { + try append(entry) + for path in LedgerResources.ancestors(of: entry.path) { + try append(.init(path: path, kind: .directory, executable: false)) + } + } + } + return result + } + + package func matchesRetainedPaths(_ root: URL) throws -> Bool { + let expected = try entries() + var remaining = Set(expected.keys.filter { $0 != Data(".".utf8) }) + func exact(_ directory: DirectoryHandle, prefix: String) throws -> Bool { + for name in try directory.names() { + let path = prefix + name + guard remaining.remove(Data(path.utf8)) != nil else { return false } + if expected[Data(path.utf8)]?.kind == .directory, + try !exact(directory.child(name), prefix: path + "/") + { + return false + } + } + return true + } + return try exact(DirectoryHandle(at: root), prefix: "") && remaining.isEmpty + } + + package func closureDigest(snapshotRoots: [String: URL]) throws -> String { + var records: [(String, Data)] = [] + for (id, resource) in resources.sorted(by: { $0.key < $1.key }) { + guard let root = snapshotRoots[id] else { + throw invalid(resource.path, "missing prepared Git input") + } + records.append((id, try ResolvedLedgerCodec.bytes(resource))) + for entry in resource.support where entry.kind == .file { + let file = try PathSafety.resolvedChild(base: root, subpath: entry.path) + let input = try TargetPrecondition.readingFile(file, maximumFileBytes: entry.byteCount) + guard let bytes = input.bytes else { + throw invalid(entry.path, "missing locked Git support") + } + records.append((id + "/" + entry.path, Data(FileHash.sha256Hex(data: bytes).utf8))) + } + } + return FileHash.hashRecords(records) + } + + /// Builds only entries owned by the ledger, even when the borrowed tree is a legacy superset. + package func assemble(from snapshotRoots: [String: URL], at output: URL) throws { + var owned: [Data: URL] = [:] + let selected = try entries() + for (id, resource) in resources.sorted(by: { $0.key < $1.key }) { + guard let root = snapshotRoots[id] else { + throw invalid(resource.path, "missing prepared Git input") + } + for entry in try LedgerResources.pinEntries(resource) { + let name = Data(entry.path.utf8) + let origin = try PathSafety.resolvedChild(base: root, subpath: entry.path) + if let prior = owned[name], entry.kind == .file, prior != origin, + try FileSystem.read(at: prior) != FileSystem.read(at: origin) + { + throw invalid(entry.path, "conflicting locked Git bytes") + } + owned[name] = origin + } + } + try FileSystem.createDirectory(at: output) + let directory = try DirectoryHandle(at: output) + for (name, entry) in selected.sorted(by: { $0.key.lexicographicallyPrecedes($1.key) }) { + try Task.checkCancellation() + if entry.path == "." { continue } + let parts = entry.path.utf8.split(separator: 47).map { String(decoding: $0, as: UTF8.self) } + let parent = try parts.dropLast().reduce(directory) { try $0.child($1) } + let basename = parts.last! + switch entry.kind { + case .directory: + try parent.makeDirectory(basename, syncParent: false) + case .symlink: + guard let link = entry.link else { throw invalid(entry.path, "missing link") } + try parent.link(basename, destination: link, syncParent: false) + case .file: + guard let origin = owned[name], + let bytes = try TargetPrecondition.readingFile(origin, maximumFileBytes: entry.byteCount) + .bytes, + bytes.count == entry.byteCount + else { throw invalid(entry.path, "locked bytes changed during preparation") } + try parent.write( + basename, data: bytes, mode: entry.executable ? 0o755 : 0o644, syncParent: false) + } + } + for resource in resources.values { + try verify(resource, in: output, authenticatingSupportFrom: output) + } + } +} diff --git a/Sources/AgentsCore/LedgerResourceLinks.swift b/Sources/AgentsCore/LedgerResourceLinks.swift index 55cbd16..3612872 100644 --- a/Sources/AgentsCore/LedgerResourceLinks.swift +++ b/Sources/AgentsCore/LedgerResourceLinks.swift @@ -5,99 +5,125 @@ extension LedgerResources { /// Supporting entries extend ownership to the source root; otherwise the selected tree is root. package static func validatedEntries(_ resource: LedgerResource) throws -> [String: LedgerEntry] { var entries: [String: LedgerEntry] = [:] - for original in resource.support - + resource.entries.map({ original in - var entry = original - if !resource.support.isEmpty { - entry.path = - original.path == "." - ? resource.path - : resource.path == "." ? original.path : resource.path + "/" + original.path - } - return entry - }) - { - try ledgerPath(original.path) - guard entries[original.path] == nil || entries[original.path] == original else { + for entry in resource.support { + try ledgerPath(entry.path) + guard entries.updateValue(entry, forKey: entry.path) == nil else { throw CoreError.invalidState("conflicting resource support") } - entries[original.path] = original } - if !resource.support.isEmpty { - let parents = resource.path.split(separator: "/").dropLast() - for count in 0...parents.count { - let path = count == 0 ? "." : parents.prefix(count).joined(separator: "/") - if entries[path] == nil { - entries[path] = .init(path: path, kind: .directory, executable: false) - } + var selected = "." + if !resource.support.isEmpty, resource.path != "." { + let parts = resource.path.utf8.split(separator: 47).map { + String(decoding: $0, as: UTF8.self) } + let parent = try walkResourcePath(parts.dropLast().joined(separator: "/")) { path in + if let entry = entries[path] { return entry } + let directory = LedgerEntry(path: path, kind: .directory, executable: false) + entries[path] = directory + return directory + } + selected = parent == "." ? parts.last! : parent + "/" + parts.last! } - for path in entries.keys where path != "." { - let parts = path.split(separator: "/") - guard entries["."]?.kind == .directory else { - throw CoreError.invalidState("resource ancestor is not a directory") + if !resource.support.isEmpty, entries["."] == nil { + entries["."] = .init(path: ".", kind: .directory, executable: false) + } + for var entry in resource.entries { + if selected != "." { + entry.path = entry.path == "." ? selected : selected + "/" + entry.path } - for count in 1.. = [entry.path] - var pending: [Step] = [.finish(entry.path)] - func parts(_ link: String?) throws -> [Step] { - guard let link, !link.isEmpty, !link.hasPrefix("/"), !link.contains("\0"), - !link.contains("\\") - else { throw CoreError.invalidState("invalid resource link") } - return link.split(separator: "/").reversed().map { .part(String($0)) } + _ = try walkResourcePath(entry.path) { entries[$0] } + } + return entries + } + + /// Locked support graphs already use source-root coordinates. + static func pinEntries(_ resource: LedgerResource) throws -> [LedgerEntry] { + let entries = try validatedEntries(resource).values + guard resource.support.isEmpty, resource.path != "." else { return Array(entries) } + return entries.map { entry in + var positioned = entry + positioned.path = entry.path == "." ? resource.path : resource.path + "/" + entry.path + return positioned + } + } + + static func ancestors(of path: String) -> [String] { + let bytes = path.utf8 + return bytes.indices.compactMap { index in + bytes[index] == 47 ? String(decoding: bytes[.. LedgerEntry?, + visit: (LedgerEntry, Bool) throws -> Void = { _, _ in } + ) throws -> String { + enum Step { + case part(String) + case finish(String) + } + func parts(_ spelling: String) -> [Step] { + spelling.utf8.split(separator: 47).reversed().map { + .part(String(decoding: $0, as: UTF8.self)) } - pending += try parts(entry.link) - while let step = pending.popLast() { - switch step { - case .finish(let link): - resolved[link] = path - active.remove(link) - case .part(let part): - let current = path.isEmpty ? "." : path.joined(separator: "/") - guard entries[current]?.kind == .directory else { - throw CoreError.invalidState("resource link traverses non-directory") - } - if part == "." { continue } - if part == ".." { - guard !path.isEmpty else { throw CoreError.invalidState("resource link escapes tree") } - path.removeLast() - continue - } - let next = (path + [part]).joined(separator: "/") - guard let target = entries[next] else { - throw CoreError.invalidState("resource link has missing support") + } + var pending = parts(spelling) + var path: [String] = [] + var active = Set() + var directory = true + var hops = 0 + while let step = pending.popLast() { + switch step { + case .finish(let link): + active.remove(link) + case .part(let part): + guard directory else { + throw CoreError.invalidState("resource link traverses non-directory") + } + if part == "." { continue } + if part == ".." { + guard path.popLast() != nil else { + throw CoreError.invalidState("resource link escapes tree") } - if target.kind == .symlink { - if let cached = resolved[next] { - path = cached - } else { - guard active.insert(next).inserted else { - throw CoreError.invalidState("resource link cycle") - } - pending.append(.finish(next)) - pending += try parts(target.link) - } - } else { - path.append(part) + continue + } + let candidate = (path + [part]).joined(separator: "/") + guard let entry = try lookup(candidate) else { + throw CoreError.invalidState("resource link has missing support: " + candidate) + } + try visit(entry, !active.isEmpty) + if entry.kind == .symlink { + guard active.insert(candidate).inserted, hops < 32 else { + throw CoreError.invalidState("resource link cycle") } + guard let link = entry.link, !link.isEmpty, !link.hasPrefix("/"), !link.contains("\0"), + !link.contains("\\") + else { throw CoreError.invalidState("invalid resource link") } + hops += 1 + pending.append(.finish(candidate)) + if link.utf8.last == 47 { pending.append(.part(".")) } + pending += parts(link) + } else { + path.append(part) + directory = entry.kind == .directory } } } - return entries + return path.isEmpty ? "." : path.joined(separator: "/") } } diff --git a/Sources/AgentsCore/LedgerResources.swift b/Sources/AgentsCore/LedgerResources.swift index 6e9eb2f..c0eb0a3 100644 --- a/Sources/AgentsCore/LedgerResources.swift +++ b/Sources/AgentsCore/LedgerResources.swift @@ -7,6 +7,24 @@ package enum LedgerResources { package static func captureLockedGit( _ resource: LedgerResource, snapshotRoot: URL ) throws -> (entries: [LedgerEntry], support: [LedgerEntry], objects: [String: Data]) { + if resource.support.contains(where: { $0.kind == .symlink }) + || resource.entries.first?.kind == .symlink + { + let file = try PathSafety.resolvedChild(base: snapshotRoot, subpath: resource.path) + let captured = try Self.capture( + file, embed: true, limits: .standard, sourceRoot: snapshotRoot) + func coordinates(_ entries: [LedgerEntry]) -> [LedgerEntry] { + entries.map { original in + var entry = original + entry.object = nil + return entry + } + } + guard captured.hash == resource.hash, coordinates(captured.entries) == resource.entries, + coordinates(captured.support) == resource.support + else { throw CoreError.invalidState("locked resource changed: " + resource.path) } + return (captured.entries, captured.support, captured.objects) + } let root = try DirectoryHandle.readDirectory(at: snapshotRoot) var limits = LedgerLimits.standard var objects: [String: Data] = [:] @@ -82,10 +100,11 @@ package enum LedgerResources { let source = ledger.sources[resource.source], source.kind == .local, let sourceLocation = source.location else { throw CoreError.invalidState("live edit skill needs a recorded local source") } - let authored = try location.resolve(roots: roots).standardizedFileURL - let root = try sourceLocation.resolve(roots: roots).standardizedFileURL - guard let sourcePath = PathSafety.realPath(root.path), - let directoryPath = PathSafety.realPath(authored.path) + let authoredPath = try location.authoredPath(roots: roots) + let sourceSpelling = try sourceLocation.authoredPath(roots: roots) + let authored = URL(fileURLWithPath: authoredPath) + guard let sourcePath = PathSafety.realPath(sourceSpelling), + let directoryPath = PathSafety.realPath(authoredPath) else { throw CoreError.notFound("live edit skill source: \(authored.path)") } guard sourcePath == "/" || directoryPath.utf8.elementsEqual(sourcePath.utf8) @@ -93,7 +112,7 @@ package enum LedgerResources { else { throw CoreError.unsafePath( "Live edit source \(authored.path) resolves outside its recorded source directory " - + "\(root.path). Point the source alias inside that directory and retry.") + + "\(sourceSpelling). Point the source alias inside that directory and retry.") } var directory: ObjCBool = false guard FileManager.default.fileExists(atPath: directoryPath, isDirectory: &directory), @@ -118,6 +137,44 @@ package enum LedgerResources { guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else { throw CoreError.notFound("locked resource") } + let selected = url.deletingLastPathComponent().resolvingSymlinksInPath() + .appendingPathComponent(url.lastPathComponent) + let root = sourceRoot?.resolvingSymlinksInPath() + func coordinate(_ path: String) throws -> LedgerEntry? { + guard let root else { return nil } + let file = try PathSafety.resolvedChild(base: root, subpath: path) + var info = stat() + guard lstat(file.path, &info) == 0 else { + if errno == ENOENT { return nil } + throw FileSystem.posixError( + errno, at: file, otherwise: .unsafePath("cannot inspect support")) + } + switch info.st_mode & S_IFMT { + case S_IFDIR: return .init(path: path, kind: .directory, executable: false) + case S_IFLNK: + let link = try FileManager.default.destinationOfSymbolicLink(atPath: file.path) + return .init(path: path, kind: .symlink, link: link, executable: false) + case S_IFREG: + return .init(path: path, kind: .file, executable: info.st_mode & 0o111 != 0) + default: throw CoreError.invalidState("unsupported locked resource entry at " + path) + } + } + if let sourceRoot, let root, url.path != sourceRoot.path { + let spelling = PathSafety.relativePath( + url.deletingLastPathComponent().path, to: sourceRoot.path) + var visited: [LedgerEntry] = [] + _ = try walkResourcePath(spelling, lookup: coordinate) { entry, throughLink in + if entry.kind == .symlink || throughLink { visited.append(entry) } + } + if visited.contains(where: { $0.kind == .symlink }) { + for entry in visited { + let file = try PathSafety.resolvedChild(base: root, subpath: entry.path) + if !PathSafety.isContained(file, in: selected) { + support[entry.path] = entry + } + } + } + } func collect(_ file: URL, path: String, supporting: Bool = false) throws { if supporting { if !visiting.insert(path).inserted { return } @@ -148,59 +205,19 @@ package enum LedgerResources { } else if type == .typeSymbolicLink { let link = try FileManager.default.destinationOfSymbolicLink(atPath: file.path) append(.init(path: path, kind: .symlink, link: link, executable: false)) - if let sourceRoot { - // Resolve components in filesystem order: an intermediate link changes the meaning - // of a following "..". Freeze every supporting link as well as the final target. - var resolved = file.deletingLastPathComponent() - enum Step { - case part(String) - case finish(String) - } - var pending: [Step] = link.split(separator: "/").reversed().map { .part(String($0)) } - var followed: Set = [file.path] - guard !link.hasPrefix("/") else { throw CoreError.unsafePath("absolute resource link") } - while let step = pending.popLast() { - guard case .part(let part) = step else { - if case .finish(let path) = step { followed.remove(path) } - continue - } - if part == "." { continue } - if part == ".." { - resolved.deleteLastPathComponent() - } else { - resolved.appendPathComponent(part) + if let root { + let spelling = PathSafety.relativePath(file.path, to: root.path) + let relative = try walkResourcePath(spelling, lookup: coordinate) { entry, throughLink in + guard entry.kind == .symlink || (entry.kind == .directory && throughLink) else { + return } - guard PathSafety.isContained(resolved, in: sourceRoot) else { - throw CoreError.unsafePath("resource link escapes source snapshot") - } - let info = try FileManager.default.attributesOfItem(atPath: resolved.path) - if info[.type] as? FileAttributeType == .typeSymbolicLink { - guard followed.insert(resolved.path).inserted else { - throw CoreError.unsafePath("resource link cycle") - } - if !PathSafety.isContained(resolved, in: url) { - try collect( - resolved, path: PathSafety.relativePath(resolved.path, to: sourceRoot.path), - supporting: true) - } - let next = try FileManager.default.destinationOfSymbolicLink(atPath: resolved.path) - guard !next.hasPrefix("/") else { - throw CoreError.unsafePath("absolute resource link") - } - pending.append(.finish(resolved.path)) - resolved.deleteLastPathComponent() - pending += next.split(separator: "/").reversed().map { .part(String($0)) } + let traversed = try PathSafety.resolvedChild(base: root, subpath: entry.path) + if !PathSafety.isContained(traversed, in: selected) { + support[entry.path] = support[entry.path] ?? entry } } - if !PathSafety.isContained(resolved, in: url) { - let relative = PathSafety.relativePath(resolved.path, to: sourceRoot.path) - let parts = relative.split(separator: "/") - for count in 1.. ResolvedLedger, limits: LedgerLimits, - transaction: FileTransaction, prepared: StatePrecondition - ) throws { - let original = try prepared.bytes(for: resolvedURL) - try transaction.replace( - resolvedURL, - with: .prepared { directory in - let bytes = - try ResolvedLedgerCodec.replacement(ledger(), existing: original, limits: limits) - ?? original - guard let bytes else { throw CoreError.invalidState("missing deferred ledger") } - let file = directory.appendingPathComponent("ledger") - try bytes.write(to: file) - return file - }, expecting: prepared.evidence(for: resolvedURL)) - } - package func ledgerBytes(limits: LedgerLimits) throws -> Data? { guard let directory = try openDirectoryIfPresent(), try directory.info(Self.resolvedFileName) != nil diff --git a/Sources/AgentsCore/LedgerValidation.swift b/Sources/AgentsCore/LedgerValidation.swift index 69b96c1..8205f8d 100644 --- a/Sources/AgentsCore/LedgerValidation.swift +++ b/Sources/AgentsCore/LedgerValidation.swift @@ -554,3 +554,21 @@ private enum NativeAddressStep: Hashable { case stableID(Data, Data) case position(Int) } + +extension ResolvedLedger { + package mutating func retainReachableContentObjects() throws { + func ownObjects(_ ledger: Self) -> Set { + var result = Set( + ledger.resources.values.flatMap { ($0.entries + $0.support).compactMap(\.object) }) + result.formUnion( + (ledger.marketplaceGraph?.nodes ?? []).filter { $0.hostedEvidence != nil }.map( + \.archiveDigest)) + return result + } + var reachable = ownObjects(self) + if let pendingDeployment { + reachable.formUnion(ownObjects(try pendingDeployment.desired(in: self))) + } + contentObjects = contentObjects.filter { reachable.contains($0.key) } + } +} diff --git a/Sources/AgentsCore/LocalGitCatalog.swift b/Sources/AgentsCore/LocalGitCatalog.swift new file mode 100644 index 0000000..7b1b7c8 --- /dev/null +++ b/Sources/AgentsCore/LocalGitCatalog.swift @@ -0,0 +1,217 @@ +import Foundation + +/// Ref selection uses the producer's transport advertisement while object reads borrow its store. +struct LocalGitCatalog { + let catalog: SourceCatalog + let advertisement: String + private let advertisedObjects: Set + let repository: URL + + init(source: URL, workspace: URL, spending: (Int) throws -> Void) throws { + let objectDirectory = try GitObjectDirectory(repository: source) + func head() throws -> String? { + let output = try ProcessRunner.isolatedGit( + ["--git-dir=" + objectDirectory.git.path, "rev-parse", "--quiet", "--verify", "HEAD"], + in: source) + return output.exitCode == 0 ? output.stdout.trimmingCharacters(in: .newlines) : nil + } + let before = try head() + advertisement = try Self.advertise(source, in: workspace) + let lines = advertisement.split(separator: "\n") + var advertised: [String: String] = [:] + var headRef: String? + for line in lines { + try spending(1) + let fields = line.split(separator: "\t", maxSplits: 1) + guard fields.count == 2 else { + throw CoreError.invalidSource("invalid local Git advertisement") + } + let name = String(fields[1]) + if fields[0].hasPrefix("ref: ") { + if name == "HEAD" { headRef = String(fields[0].dropFirst(5)) } + } else if SourceCache.isObjectID(String(fields[0])) { + advertised[name] = String(fields[0]) + } else { + throw CoreError.invalidSource("invalid advertised local object") + } + } + guard try before == head(), advertised["HEAD"].map({ $0 == before }) ?? true else { + throw CoreError.invalidState("Git HEAD changed during source resolution: " + source.path) + } + advertisedObjects = Set(advertised.values) + repository = try objectDirectory.borrow(in: workspace, named: "catalog-" + UUID().uuidString) + let refs = advertised.filter { $0.key.hasPrefix("refs/") && !$0.key.hasSuffix("^{}") } + var packed = Data("# pack-refs with: sorted\n".utf8) + // A packed namespace preserves case-distinct names even on case-insensitive volumes. + for (ref, oid) in refs.sorted(by: { $0.key.utf8.lexicographicallyPrecedes($1.key.utf8) }) { + guard Self.validRef(ref) else { + throw CoreError.invalidSource("invalid advertised Git ref") + } + packed.append(contentsOf: "\(oid) \(ref)\n".utf8) + if let peeled = advertised[ref + "^{}"] { + packed.append(contentsOf: "^\(peeled)\n".utf8) + } + } + if !refs.isEmpty { + try packed.write(to: repository.appendingPathComponent("packed-refs")) + } + if let oid = advertised["HEAD"] { + let head = + headRef.flatMap { refs[$0] == oid ? "ref: " + $0 : nil } ?? oid + try Data((head + "\n").utf8).write(to: repository.appendingPathComponent("HEAD")) + } + var tags: [String: String] = [:] + for ref in refs.keys where ref.hasPrefix("refs/tags/") { + let object = advertised[ref + "^{}"] ?? refs[ref]! + tags[String(ref.dropFirst(10))] = object + advertised[ref] = object + } + catalog = SourceCatalog(tags: tags, references: advertised) + } + + private static func validRef(_ ref: String) -> Bool { + let forbidden = "~^:?*[\\".utf8 + let bytes = ref.utf8 + return bytes.starts(with: "refs/".utf8) && bytes.last != 46 + && bytes.allSatisfy { $0 > 32 && $0 != 127 && !forbidden.contains($0) } + && !zip(bytes, bytes.dropFirst()).contains { + ($0 == 46 && $1 == 46) || ($0 == 64 && $1 == 123) + } + && bytes.split(separator: 47, omittingEmptySubsequences: false).allSatisfy { + !$0.isEmpty && $0.first != 46 && !$0.suffix(5).elementsEqual(".lock".utf8) + } + } + + private static func run( + _ arguments: [String], in directory: URL, localTransport: Bool = false + ) throws { + let output = try ProcessRunner.isolatedGit( + arguments, in: directory, localTransport: localTransport) + guard output.exitCode == 0 else { + throw GitError( + operation: .listReferences, source: "local Git catalog", stderr: output.stderr, + command: ["git"] + arguments, exitCode: output.exitCode, replacingPaths: [directory]) + } + } + + /// Expressions outside the advertised ref grammar can use only objects delivered by transport. + func transportRevision( + _ expression: String, source: URL, workspace: URL, spending: (Int) throws -> Void + ) throws -> String? { + func verifyAdvertisement() throws { + guard try Self.advertise(source, in: workspace) == advertisement else { + throw CoreError.invalidState("Git references changed during source resolution") + } + } + try verifyAdvertisement() + let clone = workspace.appendingPathComponent("transport-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: clone) } + try Self.run( + [ + "-c", "maintenance.auto=false", "-c", "gc.auto=0", + "clone", "--mirror", "--no-local", "--template=", "--", source.path, clone.path, + ], + in: workspace, localTransport: true) + let transported = try Self.advertise(clone, in: workspace).split(separator: "\n") + try spending(transported.count) + try verifyAdvertisement() + // The clone must have received the frozen objects even if a producer ref changed + // during transport and then changed back. + func objectRecords(_ lines: [Substring]) -> Set { + Set(lines.filter { !$0.hasPrefix("ref: ") }) + } + guard objectRecords(transported) == objectRecords(advertisement.split(separator: "\n")) else { + throw CoreError.invalidState("Git references changed during source resolution") + } + return try Self.revision(expression, in: clone) + } + + static func advertise(_ source: URL, in workspace: URL) throws -> String { + let arguments = ["--no-optional-locks", "ls-remote", "--symref", "--", source.path] + let output = try ProcessRunner.isolatedGit(arguments, in: workspace, localTransport: true) + guard output.exitCode == 0, output.validUTF8 else { + throw GitError( + operation: .listRemoteReferences, source: source.path, stderr: output.stderr, + command: ["git"] + arguments, exitCode: output.exitCode) + } + return output.stdout + } + + /// Git can interpret reflogs, abbreviated IDs, message searches and other expressions using + /// objects outside the advertised namespace. Only ref-rooted ancestry is provable here. + func resolvesInAdvertisement(_ expression: String) -> Bool { + let base = String(expression.prefix { $0 != "^" && $0 != "~" }) + let suffix = String(expression.dropFirst(base.count)) + guard + base == "HEAD" + || (!base.isEmpty && !base.contains("@{") && !base.contains(":") + && !base.hasPrefix("-") && !SourceCache.isObjectID(base)), + suffix.range(of: #"^(?:(?:[~^][0-9]*|\^\{(?:commit)?\}))*$"#, options: .regularExpression) + != nil + else { return false } + return [base, "refs/" + base, "refs/tags/" + base, "refs/heads/" + base].contains { + catalog.references[$0] != nil + } + } + + func admittedCommit(_ object: String) throws -> String? { + guard let commit = try revision(object) else { return nil } + if advertisedObjects.contains(object) { return commit } + guard object == commit else { return nil } + let refs = try ProcessRunner.isolatedGit( + ["for-each-ref", "--contains=" + commit, "--count=1", "--format=%(objectname)"], + in: repository) + guard refs.exitCode == 0, refs.validUTF8 else { + throw CoreError.invalidState("cannot verify Git commit reachability: " + object) + } + if !refs.stdout.isEmpty { return commit } + if let head = catalog.references["HEAD"] { + let ancestor = try ProcessRunner.isolatedGit( + ["merge-base", "--is-ancestor", commit, head], in: repository) + if ancestor.exitCode == 0 { return commit } + guard ancestor.exitCode == 1 else { + throw CoreError.invalidState("cannot verify Git ancestry from HEAD: " + object) + } + } + return nil + } + + /// A peeled tag can still name a tree or blob. Batch type checks for newly selected IDs. + func validateCommits(_ ids: Set, in workspace: URL) throws { + guard !ids.isEmpty else { return } + let file = workspace.appendingPathComponent("selected-commits") + let ordered = ids.sorted() + try Data((ordered.joined(separator: "\n") + "\n").utf8).write(to: file) + let input = try FileHandle(forReadingFrom: file) + defer { try? input.close() } + let args = ["cat-file", "--batch-check=%(objectname) %(objecttype)"] + let output = try ProcessRunner.isolatedGit(args, in: repository, input: input) + let records = output.stdout.split(separator: "\n") + guard output.exitCode == 0, output.validUTF8, records.count == ids.count else { + throw CoreError.invalidState("cannot verify selected Git commits") + } + for (id, record) in zip(ordered, records) where record != "\(id) commit" { + throw CoreError.invalidState("Git selection is not a commit: " + id) + } + } + + func revision(_ expression: String) throws -> String? { + try Self.revision(expression, in: repository) + } + + static func revision(_ expression: String, in repository: URL) throws -> String? { + let args = [ + "rev-parse", "--quiet", "--verify", "--end-of-options", expression + "^{commit}", + ] + let output = try ProcessRunner.isolatedGit(args, in: repository) + if output.exitCode == 1 { return nil } + guard output.exitCode == 0, output.validUTF8, + SourceCache.isObjectID(output.stdout.trimmingCharacters(in: .newlines)) + else { + throw GitError( + operation: .resolveRevision(revision: expression), source: repository.path, + stderr: output.stderr, command: ["git"] + args, exitCode: output.exitCode) + } + return output.stdout.trimmingCharacters(in: .newlines) + } +} diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift index 461019b..862e446 100644 --- a/Sources/AgentsCore/NativeTargetCoordination.swift +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -982,7 +982,7 @@ final class TransactionLockContext { absentRoots: [AbsentSharedRoot] = [], admissions: [SharedResource] = [], requestedRoutes: Set = [], installations: [SkillInstallationTarget] = [] ) { - scopeURL = store.directory.standardizedFileURL + scopeURL = store.physicalDirectory self.resources = resources self.admissions = admissions.isEmpty ? resources : admissions resourcesByIdentity = Dictionary( @@ -1005,7 +1005,7 @@ final class TransactionLockContext { static func current(_ store: StateStore) -> TransactionLockContext? { let context = Thread.current.threadDictionary[threadKey] as? TransactionLockContext - return context?.scopeURL.path == store.directory.standardizedFileURL.path ? context : nil + return context?.scopeURL.path == store.physicalDirectory.path ? context : nil } func run(_ body: () throws -> T) throws -> T { diff --git a/Sources/AgentsCore/ProcessRunner.swift b/Sources/AgentsCore/ProcessRunner.swift index 119c9e8..209b003 100644 --- a/Sources/AgentsCore/ProcessRunner.swift +++ b/Sources/AgentsCore/ProcessRunner.swift @@ -5,25 +5,51 @@ package struct ProcessOutput: Equatable, Sendable { package var stdout: String package var stderr: String package var exitCode: Int32 + var validUTF8 = true } package enum ProcessRunner { /// Runs Git plumbing with literal arguments and without inherited Git overrides. package static func isolatedGit( - _ arguments: [String], in directory: URL, inheritingLock descriptor: Int32? = nil + _ arguments: [String], in directory: URL, inheritingLock descriptor: Int32? = nil, + input: FileHandle? = nil, localTransport: Bool = false, + output: ((FileHandle) throws -> Void)? = nil ) throws -> ProcessOutput { - let environment = [ + try isolatedGit( + arguments, in: directory, inheritingLock: descriptor, input: input, + localTransport: localTransport, useScopedTree: false, output: output) + } + + /// Archives using the replacement tree generated in a private, object-only repository. + static func archiveScopedGitTree( + _ arguments: [String], in directory: URL, inheritingLock descriptor: Int32?, + output: @escaping (FileHandle) throws -> Void + ) throws -> ProcessOutput { + try isolatedGit( + arguments, in: directory, inheritingLock: descriptor, input: nil, + localTransport: false, useScopedTree: true, output: output) + } + + private static func isolatedGit( + _ arguments: [String], in directory: URL, inheritingLock descriptor: Int32?, + input: FileHandle?, localTransport: Bool, useScopedTree: Bool, + output: ((FileHandle) throws -> Void)? + ) throws -> ProcessOutput { + var environment = [ "PATH": ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin", - "LC_ALL": "C", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1", - "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", - "GIT_NO_LAZY_FETCH": "1", "GIT_ALLOW_PROTOCOL": "", "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", "TZ": "UTC", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1", + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_LAZY_FETCH": "1", "GIT_ALLOW_PROTOCOL": localTransport ? "file" : "", + "GIT_TERMINAL_PROMPT": "0", "GIT_CEILING_DIRECTORIES": directory.deletingLastPathComponent().path, ] + if !useScopedTree { environment["GIT_NO_REPLACE_OBJECTS"] = "1" } return try execute( "/usr/bin/env", arguments: [ "git", "-c", "core.attributesFile=/dev/null", "-c", "core.hooksPath=/dev/null", - ] + arguments, workingDirectory: directory, environment: environment, lock: descriptor) + ] + arguments, workingDirectory: directory, environment: environment, lock: descriptor, + input: input, output: output) } @discardableResult @@ -38,7 +64,7 @@ package enum ProcessRunner { throw CoreError.commandFailed( ([executable] + arguments).joined(separator: " ") + "\n" + output.stderr) } - return output + return ProcessOutput(stdout: output.stdout, stderr: output.stderr, exitCode: output.exitCode) } @discardableResult @@ -134,26 +160,32 @@ package enum ProcessRunner { static func execute( _ executable: String, arguments: [String], workingDirectory: URL?, - environment: [String: String], lock: Int32? + environment: [String: String], lock: Int32?, input: FileHandle? = nil, + output: ((FileHandle) throws -> Void)? = nil ) throws -> ProcessOutput { if let lock { return try spawn( executable, arguments: arguments, workingDirectory: workingDirectory, - environment: environment, lock: lock) + environment: environment, lock: lock, input: input, output: output) } return try runProcess( - executable, arguments: arguments, workingDirectory: workingDirectory, environment: environment + executable, arguments: arguments, workingDirectory: workingDirectory, + environment: environment, + input: input, output: output ) } private static func runProcess( - _ executable: String, arguments: [String], workingDirectory: URL?, environment: [String: String] + _ executable: String, arguments: [String], workingDirectory: URL?, + environment: [String: String], + input: FileHandle?, output: ((FileHandle) throws -> Void)? ) throws -> ProcessOutput { let process = Process() process.executableURL = URL(fileURLWithPath: executable) process.arguments = arguments process.currentDirectoryURL = workingDirectory process.environment = environment + if let input { process.standardInput = input } let stdout = Pipe() let stderr = Pipe() @@ -161,14 +193,17 @@ package enum ProcessRunner { process.standardError = stderr try process.run() - let stdoutReader = PipeReader(stdout.fileHandleForReading) let stderrReader = PipeReader(stderr.fileHandleForReading) + let stdoutReader = output == nil ? PipeReader(stdout.fileHandleForReading) : nil + let streamed = stream(stdout.fileHandleForReading, to: output) process.waitUntilExit() + if process.terminationStatus == 0 { try streamed.get() } + let text = stdoutReader.map { String(data: $0.waitForOutput(), encoding: .utf8) } ?? "" return ProcessOutput( - stdout: String(data: stdoutReader.waitForOutput(), encoding: .utf8) ?? "", + stdout: text ?? "", stderr: String(data: stderrReader.waitForOutput(), encoding: .utf8) ?? "", - exitCode: process.terminationStatus + exitCode: process.terminationStatus, validUTF8: text != nil ) } @@ -177,7 +212,8 @@ package enum ProcessRunner { /// CLOEXEC in the parent where another thread could concurrently launch a child. private static func spawn( _ executable: String, arguments: [String], workingDirectory: URL?, - environment: [String: String], lock: Int32 + environment: [String: String], lock: Int32, input: FileHandle?, + output: ((FileHandle) throws -> Void)? ) throws -> ProcessOutput { func check(_ error: Int32) throws { if error != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(error)) } @@ -208,6 +244,9 @@ package enum ProcessRunner { // source, even when open/pipe allocated descriptors 0, 1 or 2 in the host. let inheritedLock = try duplicate(lock) defer { close(inheritedLock) } + let stdin = + try input.map { try duplicate($0.fileDescriptor) } ?? (inputIsOpen ? STDIN_FILENO : -1) + defer { if stdin > STDIN_FILENO { close(stdin) } } let output = try duplicate(stdout.fileHandleForWriting.fileDescriptor) defer { close(output) } let error = try duplicate(stderr.fileHandleForWriting.fileDescriptor) @@ -215,7 +254,7 @@ package enum ProcessRunner { func launch(_ directory: UnsafePointer?) throws { try check( platform_spawn( - &pid, executable, argv, environment, directory, inheritedLock, inputIsOpen, output, + &pid, executable, argv, environment, directory, inheritedLock, stdin, output, error)) } if let workingDirectory { @@ -226,17 +265,32 @@ package enum ProcessRunner { }() stdout.fileHandleForWriting.closeFile() stderr.fileHandleForWriting.closeFile() - let stdoutReader = PipeReader(stdout.fileHandleForReading) let stderrReader = PipeReader(stderr.fileHandleForReading) + let stdoutReader = output == nil ? PipeReader(stdout.fileHandleForReading) : nil + let streamed = stream(stdout.fileHandleForReading, to: output) var status: Int32 = 0 while waitpid(pid, &status, 0) < 0 { if errno != EINTR { try check(errno) } } let signal = status & 0x7f + if status == 0 { try streamed.get() } + let text = stdoutReader.map { String(data: $0.waitForOutput(), encoding: .utf8) } ?? "" return ProcessOutput( - stdout: String(data: stdoutReader.waitForOutput(), encoding: .utf8) ?? "", + stdout: text ?? "", stderr: String(data: stderrReader.waitForOutput(), encoding: .utf8) ?? "", - exitCode: signal == 0 ? (status >> 8) & 0xff : 128 + signal) + exitCode: signal == 0 ? (status >> 8) & 0xff : 128 + signal, validUTF8: text != nil) + } + + private static func stream( + _ handle: FileHandle, to output: ((FileHandle) throws -> Void)? + ) -> Result { + guard let output else { return .success(()) } + defer { try? handle.close() } + return Result { + try output(handle) + // A tar consumer can stop at its end marker while Git still writes record padding. + while let padding = try handle.read(upToCount: 65_536), !padding.isEmpty {} + } } } diff --git a/Sources/AgentsCore/ResolvedLedger.swift b/Sources/AgentsCore/ResolvedLedger.swift index 9fbc8af..0e7b653 100644 --- a/Sources/AgentsCore/ResolvedLedger.swift +++ b/Sources/AgentsCore/ResolvedLedger.swift @@ -189,6 +189,29 @@ public struct LedgerLocation: Codable, Equatable, Hashable, Sendable { public var root: String? public var path: String + /// Compares authored coordinates while preserving the filesystem meaning of links and "..". + package func authoredPath(roots: [String: URL]) throws -> String { + let spelling = Self.authoredSpelling(path) + try Self(kind: kind, root: root, path: spelling).validate() + if kind == .absolute { return spelling } + guard let root, let directory = roots[root] else { + throw CoreError.invalidState("missing registered ledger root") + } + return Self.authoredSpelling(directory.path + "/" + spelling) + } + + package func appendingAuthoredPath(_ relative: String) -> Self { + guard relative != "." else { return self } + return .init(kind: kind, root: root, path: Self.authoredSpelling(path + "/" + relative)) + } + + private static func authoredSpelling(_ path: String) -> String { + let parts = path.utf8.split(separator: 47).filter { !$0.elementsEqual(".".utf8) } + let spelling = parts.map { String(decoding: $0, as: UTF8.self) }.joined(separator: "/") + if path.utf8.first == 47 { return "/" + spelling } + return spelling.isEmpty ? "." : spelling + } + package func resolve(roots: [String: URL]) throws -> URL { try validate() if kind == .absolute { return URL(fileURLWithPath: path) } diff --git a/Sources/AgentsCore/RetentionReferences.swift b/Sources/AgentsCore/RetentionReferences.swift index 5f20a5c..f74c8f5 100644 --- a/Sources/AgentsCore/RetentionReferences.swift +++ b/Sources/AgentsCore/RetentionReferences.swift @@ -7,9 +7,12 @@ package struct RetentionReferences: Sendable { package var revision: String } var archives: Set = [] - package var git: Set = [] + package private(set) var requiredGitObjects: Set = [] + private var provenanceGitRefs: Set = [] + package var protectedGitRefs: Set { requiredGitObjects.union(provenanceGitRefs) } package var artifacts: Set = [] package var live: [URL] = [] + package var liveAliases: [URL] = [] package var sourceLocations: [String: String] = [:] package init() {} @@ -19,8 +22,46 @@ package struct RetentionReferences: Sendable { if let pending = ledger.pendingDeployment { self = try RetentionReferences(ledger: pending.desired(in: ledger), roots: roots) } - // Every source is part of the accepted closure, including empty groups and container parents. - for source in ledger.sources.values { + func root(_ id: String) -> String { + var id = id + while let parent = ledger.sources[id]?.container { id = parent } + return id + } + var provenance = Set() + var independent = Set(ledger.groups.map { root($0.source) }) + let marketplace = Set( + (ledger.marketplacePackages ?? []).flatMap(\.componentRecords) + + (ledger.marketplaceGraph?.nodes ?? []).flatMap(\.componentRecords)) + independent.formUnion( + ledger.resources.values.filter { $0.kind == .git }.map { root($0.source) }) + let occurrences = Dictionary(grouping: ledger.occurrences, by: \.component) + for (id, component) in ledger.components { + let source = root(component.source) + let exact = ledger.sources[source].map { SourceCache.isObjectID($0.revision) } ?? false + let inputs = component.resources.compactMap { ledger.resources[$0] } + let selfContained = + exact && component.kind == "instructions" + && component.recipients.contains(.antigravity) && !inputs.isEmpty + && inputs.allSatisfy { resource in + resource.kind == .embedded + && (resource.entries + resource.support).allSatisfy { + $0.kind != .file || $0.object.flatMap { ledger.contentObjects[$0] } != nil + } + } + let dependencies = + occurrences[id, default: []].flatMap { occurrence in + occurrence.dependencies + [occurrence.declaringSource] + + (occurrence.pluginExpansion.map { [$0.source] } ?? []) + }.map(root) + [root(component.declaringSource)] + inputs.map { root($0.source) } + independent.formUnion(dependencies.filter { $0 != source || !selfContained }) + if selfContained && !marketplace.contains(id) { + provenance.insert(source) + } else { + independent.insert(source) + } + } + // Empty groups and independent edges still own exact objects even alongside legacy rules. + for (id, source) in ledger.sources { guard source.container == nil else { continue } if let archive = source.archive, let transport = source.transport { archives.insert(.init(transport: transport, archive: archive)) @@ -39,14 +80,44 @@ package struct RetentionReferences: Sendable { } else { throw CoreError.invalidState("missing retained source coordinates") } - git.insert(.init(source: identity, revision: source.revision)) + let pin = Git(source: identity, revision: source.revision) + if provenance.contains(id), !independent.contains(id) { + provenanceGitRefs.insert(pin) + } else { + requiredGitObjects.insert(pin) + } sourceLocations[identity] = location } artifacts.formUnion(ledger.resources.filter { $0.value.kind != .liveEdit }.keys) for resource in ledger.resources.values { if let artifact = resource.artifact { retain(artifact) } if resource.kind == .liveEdit, let location = resource.location { - live.append(try location.resolve(roots: roots).resolvingSymlinksInPath()) + let authored = try location.authoredPath(roots: roots) + do { + let observed = try LedgerResources.liveEditSource(resource, ledger: ledger, roots: roots) + live.append(observed.directory) + } catch CoreError.notFound { + // A formerly live directory can be removed by reconciliation. Its authored + // coordinates still protect the path until that generation is replaced. + let url = URL(fileURLWithPath: authored) + let parent = (authored as NSString).deletingLastPathComponent + live.append( + PathSafety.realPath(parent).map { + URL(fileURLWithPath: $0).appendingPathComponent(url.lastPathComponent) + } ?? url) + } + var spelling = "" + for part in authored.utf8.split(separator: 47) { + spelling += "/" + String(decoding: part, as: UTF8.self) + var info = stat() + if lstat(spelling, &info) == 0, info.st_mode & S_IFMT == S_IFLNK, + let parent = PathSafety.realPath((spelling as NSString).deletingLastPathComponent) + { + liveAliases.append( + URL(fileURLWithPath: parent).appendingPathComponent( + String(decoding: part, as: UTF8.self))) + } + } } } } @@ -58,7 +129,7 @@ package struct RetentionReferences: Sendable { sourceLocations[id] = id.hasPrefix("local:") ? String(id.dropFirst(6)) : id } switch source.seen { - case .revision(let revision): git.insert(.init(source: id, revision: revision)) + case .revision(let revision): requiredGitObjects.insert(.init(source: id, revision: revision)) case .artifacts(let objects): artifacts.formUnion(objects.values) } } diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index 4a057cf..4766796 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -21,8 +21,8 @@ package struct SourceRevision: Equatable, Sendable { package struct SourceCache { package let store: StateStore - private let sourcePolicy: EffectiveSourcePolicy - private let requireRecordedTransport: Bool + let sourcePolicy: EffectiveSourcePolicy + let requireRecordedTransport: Bool private let checkpoint: (String) throws -> Void private let acquisitions: GitAcquisitionCaptures? @@ -123,57 +123,11 @@ package struct SourceCache { { return try body(tree, true) } - let location = declared.location - let root = FileManager.default.temporaryDirectory.appendingPathComponent( - "agents-snapshot-" + UUID().uuidString) - try FileSystem.createDirectory(at: root) - defer { try? FileManager.default.removeItem(at: root) } - func export(_ repository: URL, lock: Int32?) throws -> URL? { - let arguments = [ - "--no-optional-locks", "rev-parse", "--quiet", "--verify", revision + "^{commit}", - ] - do { - let result = - try lockedPaths == nil - ? ProcessRunner.git( - Self.gitOptions + ["-C", repository.path] + arguments, - operation: .resolveRevision(revision: revision), source: location, - inheritingLock: lock, offline: true) - : ProcessRunner.isolatedGit(arguments, in: repository, inheritingLock: lock) - guard result.exitCode == 0, - result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == revision - else { - return nil - } - } catch let error as GitError where error.exitCode == 1 && error.stderr.isEmpty { - return nil - } - return try extract( - revision: revision, mirror: repository, source: location, root: root, lock: lock, - offline: true, lockedPaths: lockedPaths) - } - if let tree = try withExistingMirror( - sourceID: sourceID, - { mirror, lock in - try export(mirror, lock: lock) - }) ?? nil - { - return try body(tree, false) - } - if source.kind == .local { - let repository = URL(fileURLWithPath: location) - if FileManager.default.fileExists(atPath: repository.appendingPathComponent(".git").path), - let tree = try export(repository, lock: nil) - { - return try body(tree, false) - } - } - if let acquisition = anonymousAcquisition(declared), - let pack = try acquisition.exact(revision, offline: true) - { - return try withAnonymousTree(acquisition, pack: pack) { try body($0, false) } - } - throw CoreError.notFound("cached Git commit \(revision) for \(sourceID)") + return try withGitSelection( + declared, revision: revision, + selections: (lockedPaths ?? ["."]).map { .init(path: $0) }, + offline: true + ) { try body($0, false) } } package func artifactURL(digest: String) throws -> URL { @@ -250,7 +204,7 @@ package struct SourceCache { ], operation: .resolveRevision(revision: expression), source: source.location, lock: descriptor) - } catch let error as GitError where error.exitCode == 1 && error.stderr.isEmpty { + } catch let error as GitError where error.exitCode == 1 { return nil } } ?? nil @@ -315,49 +269,61 @@ package struct SourceCache { func retainWatchRevision(sourceID: String, source: String, revision: String) throws { let url = mirrorURL(sourceID: sourceID) try withMirrorLock(at: url) { descriptor in - try beginWatchReferenceUpdate() - let mirror = try DirectoryHandle(at: url) - let objects = try mirror.child("objects") - if try objects.info("info") != nil { - let info = try objects.child("info") - if try info.info("alternates") != nil, try !info.read("alternates").isEmpty { - throw CoreError.invalidState("watch requires self-contained mirror objects") - } + try retainWatchRevisions([revision], at: url, source: source, descriptor: descriptor) + } + } + + private func retainWatchRevisions( + _ revisions: [String], at url: URL, source: String, descriptor: Int32 + ) throws { + try beginWatchReferenceUpdate() + let mirror = try DirectoryHandle(at: url) + let objects = try mirror.child("objects") + if try objects.info("info") != nil { + let info = try objects.child("info") + if try info.info("alternates") != nil, try !info.read("alternates").isEmpty { + throw CoreError.invalidState("watch requires self-contained mirror objects") } - // Explicit barriers cover pre-existing objects as well as newly fetched objects. - func syncObjects(_ directory: DirectoryHandle) throws { - for name in try directory.names() { - if try (directory.info(name)?.st_mode ?? 0) & 0o170000 == 0o040000 { - try syncObjects(directory.child(name)) - } else { - try directory.syncFile(name) - } + } + // Explicit barriers cover pre-existing objects as well as newly fetched objects. + func syncObjects(_ directory: DirectoryHandle) throws { + for name in try directory.names() { + if try (directory.info(name)?.st_mode ?? 0) & 0o170000 == 0o040000 { + try syncObjects(directory.child(name)) + } else { + try directory.syncFile(name) } - try directory.sync() } - try syncObjects(objects) - try checkpoint("watch.objects.synced") - let refs = try mirror.child("refs") - if try refs.info("agents-watch") == nil { try refs.makeDirectory("agents-watch") } - let retained = try refs.child("agents-watch") + try directory.sync() + } + try syncObjects(objects) + try checkpoint("watch.objects.synced") + let refs = try mirror.child("refs") + if try refs.info("agents-watch") == nil { try refs.makeDirectory("agents-watch") } + let retained = try refs.child("agents-watch") + for (index, revision) in revisions.enumerated() { _ = try git( url, ["update-ref", "--no-deref", "refs/agents-watch/" + revision, revision], operation: .updateReference, source: source, lock: descriptor) - try checkpoint("watch.ref.updated") - // Updating an already packed ref to the same commit can leave it packed. - if try retained.info(revision) != nil { try retained.syncFile(revision) } - if try mirror.info("packed-refs") != nil { try mirror.syncFile("packed-refs") } - try retained.sync() - try checkpoint("watch.ref.synced") - try refs.sync() - try mirror.syncFile("config") - try mirror.syncFile("HEAD") - let mirrors = try DirectoryHandle(at: url.deletingLastPathComponent()) - try mirrors.sync() - try DirectoryHandle(at: store.cacheDirectory).sync() - try store.openDirectoryIfPresent()?.sync() - try checkpoint("watch.mirror.synced") - } + try checkpoint(revisions.count == 1 ? "watch.ref.updated" : "watch.ref.\(index).updated") + } + // Updating an already packed ref to the same commit can leave it packed. + for revision in revisions where try retained.info(revision) != nil { + try retained.syncFile(revision) + } + if try mirror.info("packed-refs") != nil { try mirror.syncFile("packed-refs") } + try retained.sync() + for index in revisions.indices { + try checkpoint(revisions.count == 1 ? "watch.ref.synced" : "watch.ref.\(index).synced") + } + try refs.sync() + try mirror.syncFile("config") + try mirror.syncFile("HEAD") + let mirrors = try DirectoryHandle(at: url.deletingLastPathComponent()) + try mirrors.sync() + try DirectoryHandle(at: store.cacheDirectory).sync() + try store.openDirectoryIfPresent()?.sync() + try checkpoint("watch.mirror.synced") } /// The marker precedes ref preparation or a state change that can release an existing pin. @@ -400,7 +366,7 @@ package struct SourceCache { (key($0.key) + ".git", $0.value) }) var retained: [String: Set] = [:] - for pin in references.git { + for pin in references.protectedGitRefs { retained[key(pin.source) + ".git", default: []].insert(pin.revision) } // Even a manually supplied generation must reach storage before its obsolete pins go away. @@ -510,36 +476,6 @@ package struct SourceCache { try syncDirectories(mirror) } - package func materialize(sourceID: String, source: LockedSource, revision: String) throws -> URL { - guard revision.range(of: #"^[0-9a-f]{40}([0-9a-f]{24})?$"#, options: .regularExpression) != nil - else { - throw CoreError.invalidState("materialization requires an exact commit") - } - try requireGit(declaration(sourceID: sourceID, source: source)) - try validatePath(materializedURL(sourceID: sourceID, revision: revision)) - try validatePath(store.cacheDirectory.appendingPathComponent("locks")) - return try FileLock.withLock( - at: store.cacheDirectory.appendingPathComponent("locks/\(key(sourceID))-\(revision).lock") - ) { - let destination = materializedURL(sourceID: sourceID, revision: revision) - if FileManager.default.fileExists(atPath: destination.path) { return destination } - let mirror = try pinnedMirror(sourceID: sourceID, source: source, revision: revision) - let transaction = FileTransaction(store: store, checkpoint: checkpoint) - try transaction.replace( - destination, - with: .prepared { work in - try extract( - revision: revision, mirror: mirror, - source: declaration(sourceID: sourceID, source: source).location, root: work) - }) - try transaction.commit() - return destination - } - } - - /// Inspection extracts to disposable storage; only applied operations retain materializations. - /// With `cacheSource: false`, existing exact pins are read without mutation; - /// new mirrors and their locks live in disposable storage. package func withResolvedSnapshot( _ source: SourceDeclaration, cacheSource: Bool = true, _ body: (SourceRevision, URL) throws -> T @@ -620,16 +556,19 @@ package struct SourceCache { } private func withAnonymousTree( - _ acquisition: GitAcquisition, pack: GitAcquisition.Pack, _ body: (URL) throws -> T + _ acquisition: GitAcquisition, pack: GitAcquisition.Pack, + selections: [GitTreeArchive.Selection] = [.init(path: ".")], historical: Bool = false, + uncoveredSupport: Set = [], observingCoverage: ((GitTreeArchive.Coverage) -> Void)? = nil, + _ body: (URL) throws -> T ) throws -> T { try acquisition.withVerifiedRepository(pack) { repository, _ in - let root = FileManager.default.temporaryDirectory.appendingPathComponent( - "agents-snapshot-" + UUID().uuidString) - try FileSystem.createDirectory(at: root) + let root = try Self.privateWorkspace(prefix: "agents-snapshot-") defer { try? FileManager.default.removeItem(at: root) } - let archive = root.appendingPathComponent("tree.tar") - try acquisition.archive(pack.revision, repository: repository, to: archive) - return try body(unpack(archive, at: root)) + return try body( + extract( + revision: pack.revision, mirror: repository, source: acquisition.url, root: root, + selections: selections, historical: historical, uncoveredSupport: uncoveredSupport, + observingCoverage: observingCoverage)) } } @@ -707,20 +646,21 @@ package struct SourceCache { package func withSnapshot( sourceID: String, source: LockedSource, revision: String, _ body: (URL) throws -> T ) throws -> T { - try requireGit(declaration(sourceID: sourceID, source: source)) - let mirror = try pinnedMirror(sourceID: sourceID, source: source, revision: revision) - let root = FileManager.default.temporaryDirectory.appendingPathComponent( - "agents-snapshot-" + UUID().uuidString) - try FileSystem.createDirectory(at: root) + let declared = try declaration(sourceID: sourceID, source: source) + try requireGit(declared) + let root = try Self.privateWorkspace(prefix: "agents-snapshot-") defer { try? FileManager.default.removeItem(at: root) } - return try body( - extract( - revision: revision, mirror: mirror, - source: declaration(sourceID: sourceID, source: source).location, root: root)) + let tree = try withMirrorLock(at: mirrorURL(sourceID: sourceID)) { lock in + let mirror = try pinnedMirror( + sourceID: sourceID, source: source, revision: revision, offline: false, lock: lock) + return try extract( + revision: revision, mirror: mirror, source: declared.location, root: root, lock: lock) + } + return try body(tree) } private func pinnedMirror( - sourceID: String, source: LockedSource, revision: String, offline: Bool = false + sourceID: String, source: LockedSource, revision: String, offline: Bool, lock: Int32 ) throws -> URL { guard revision.range(of: #"^[0-9a-f]{40}([0-9a-f]{24})?$"#, options: .regularExpression) != nil else { @@ -733,25 +673,25 @@ package struct SourceCache { if (try? git( mirror, ["cat-file", "-e", revision + "^{commit}"], operation: .resolveRevision(revision: revision), source: declaration.location, - offline: offline)) == nil + lock: lock, offline: offline)) == nil { if let acquisition = anonymousAcquisition(declaration), let pack = try attemptAnonymous({ try acquisition.exact(revision, offline: offline) }), pack.revision == revision { - mirror = try importAnonymous(pack, from: acquisition, sourceID: sourceID) + mirror = try importAnonymous(pack, from: acquisition, into: mirror) acquisition.remember(pack) } else if offline && declaration.kind != .local { throw CoreError.notFound("cached Git commit \(revision) for \(sourceID)") } else { - mirror = try fetch(declaration, id: sourceID) + mirror = try fetchMirror(declaration, id: sourceID, lock: lock) } } guard try git( mirror, ["rev-parse", "--verify", revision + "^{commit}"], operation: .resolveRevision(revision: revision), source: declaration.location, - offline: offline) == revision + lock: lock, offline: offline) == revision else { throw CoreError.invalidState("locked commit is unavailable") } @@ -765,26 +705,33 @@ package struct SourceCache { ) throws -> URL { let mirror = mirrorURL(sourceID: sourceID) return try withMirrorLock(at: mirror) { _ in - try acquisition.withVerifiedRepository(pack) { repository, stem in - let parent = try DirectoryHandle(at: mirror.deletingLastPathComponent(), create: true) - let name = mirror.lastPathComponent - let existing = try parent.directory(name) - let directory: DirectoryHandle - if let existing { - directory = existing - } else { - let staging = name + ".staging-" + UUID().uuidString - let provisioned = try parent.makeDirectory(staging) - let identity = try provisioned.objectIdentity - defer { try? parent.remove(staging, identity: identity) } - try acquisition.initializeMirror(at: provisioned.url, object: pack.revision) - try installPack(repository, stem: stem, into: provisioned) - try parent.move(staging, to: parent, named: name, mode: .exclusive) - return mirror - } - try installPack(repository, stem: stem, into: directory) + try importAnonymous(pack, from: acquisition, into: mirror) + } + } + + /// The caller holds this mirror's lock through installation. + private func importAnonymous( + _ pack: GitAcquisition.Pack, from acquisition: GitAcquisition, into mirror: URL + ) throws -> URL { + try acquisition.withVerifiedRepository(pack) { repository, stem in + let parent = try DirectoryHandle(at: mirror.deletingLastPathComponent(), create: true) + let name = mirror.lastPathComponent + let existing = try parent.directory(name) + let directory: DirectoryHandle + if let existing { + directory = existing + } else { + let staging = name + ".staging-" + UUID().uuidString + let provisioned = try parent.makeDirectory(staging) + let identity = try provisioned.objectIdentity + defer { try? parent.remove(staging, identity: identity) } + try acquisition.initializeMirror(at: provisioned.url, object: pack.revision) + try installPack(repository, stem: stem, into: provisioned) + try parent.move(staging, to: parent, named: name, mode: .exclusive) return mirror } + try installPack(repository, stem: stem, into: directory) + return mirror } } @@ -821,42 +768,112 @@ package struct SourceCache { private func extract( revision: String, mirror: URL, source: String, root: URL, lock: Int32? = nil, - offline: Bool = false, lockedPaths: [String]? = nil + selections: [GitTreeArchive.Selection] = [.init(path: ".")], historical: Bool = false, + uncoveredSupport: Set = [], observingCoverage: ((GitTreeArchive.Coverage) -> Void)? = nil ) throws -> URL { - let archive = root.appendingPathComponent("tree.tar") - let arguments = [ - "--no-optional-locks", "archive", "--format=tar", "--output=" + archive.path, revision, - ] - if let lockedPaths { - let selection = lockedPaths.contains(".") ? [] : ["--"] + lockedPaths - let result = try ProcessRunner.isolatedGit( - ["--literal-pathspecs"] + arguments + selection, in: mirror, inheritingLock: lock) - guard result.exitCode == 0 else { throw CoreError.notFound("locked producer Git paths") } - } else if offline { - _ = try ProcessRunner.git( - Self.gitOptions + ["-C", mirror.path] + arguments, - operation: .extractRevision, source: source, replacingPaths: [root, mirror], - inheritingLock: lock, offline: true) - } else if let lock { - _ = try git( - mirror, arguments, operation: .extractRevision, source: source, - replacingPaths: [root], lock: lock) - } else { - _ = try git( - mirror, arguments, operation: .extractRevision, source: source, - replacingPaths: [root]) + let objects = try GitObjectDirectory(repository: mirror, source: source, lock: lock) + let archive = try objects.borrow(in: root, named: "archive") + if historical { + // A compatibility read may try currently available refs. Callers must prove its bytes + // against the locked hashes before interpreting any result as historical evidence. + let args = ["for-each-ref", "--format=%(objectname) %(refname)", "refs/tags", "refs/heads"] + let output = try ProcessRunner.isolatedGit(args, in: mirror, inheritingLock: lock) + guard output.exitCode == 0, output.validUTF8 else { + throw GitError( + operation: .listReferences, source: source, stderr: output.stderr, + command: ["git"] + args, exitCode: output.exitCode, replacingPaths: [mirror, root]) + } + try Data(output.stdout.utf8).write(to: archive.appendingPathComponent("packed-refs")) } - return try unpack(archive, at: root) - } - - private func unpack(_ archive: URL, at root: URL) throws -> URL { let tree = root.appendingPathComponent("tree") - try FileSystem.createDirectory(at: tree) - try ProcessRunner.unpackGitArchive(archive, into: tree) - try validateTree(tree) + try GitTreeArchive( + repository: archive, workspace: root, revision: revision, source: source, lock: lock, + historical: historical, committedAttributesOnly: true + ).extract( + selections, into: tree, uncoveredSupport: uncoveredSupport, + observingCoverage: observingCoverage) return tree } + static func isLocalRepository(_ root: URL) throws -> Bool { + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: root.path, isDirectory: &directory), + directory.boolValue + else { return false } + let manager = FileManager.default + var candidates: [String] = [] + if manager.fileExists(atPath: root.appendingPathComponent(".git").path) { + candidates.append(".git") + } + var head = stat() + if lstat(root.appendingPathComponent("HEAD").path, &head) == 0, + manager.fileExists(atPath: root.appendingPathComponent("objects").path) + || manager.fileExists(atPath: root.appendingPathComponent("commondir").path) + { + candidates.append(".") + } + // Both --resolve-git-dir forms are local to this path, rather than searching parents. + return try candidates.contains { + try ProcessRunner.isolatedGit(["rev-parse", "--resolve-git-dir", $0], in: root).exitCode == 0 + } + } + + /// Reads selected entries from an exact object store, with the mirror lock held during archive. + func withGitSelection( + _ source: SourceDeclaration, revision: String, selections: [GitTreeArchive.Selection], + offline: Bool, historical: Bool = false, uncoveredSupport: Set = [], + observingCoverage: ((GitTreeArchive.Coverage) -> Void)? = nil, + _ body: (URL) throws -> T + ) throws -> T { + try requireGit(source) + let id = try source.identity(environment: store.environment) + let root = try Self.privateWorkspace(prefix: "agents-snapshot-") + defer { try? FileManager.default.removeItem(at: root) } + func read(_ repository: URL, lock: Int32?) throws -> T? { + let tree: URL + do { + tree = try extract( + revision: revision, mirror: repository, source: source.location, root: root, lock: lock, + selections: selections, historical: historical, uncoveredSupport: uncoveredSupport, + observingCoverage: observingCoverage) + } catch is GitTreeArchive.MissingCommit { + return nil + } + return try body(tree) + } + if historical, source.kind == .local { + let local = source.localURL(environment: store.environment) + if try Self.isLocalRepository(local), let found = try read(local, lock: nil) { return found } + } + if let found = try withExistingMirror(sourceID: id, { try read($0, lock: $1) }) ?? nil { + return found + } + if source.kind == .local { + let local = source.localURL(environment: store.environment) + if try Self.isLocalRepository(local), let found = try read(local, lock: nil) { return found } + } + if let acquisition = anonymousAcquisition(source), + let pack = try attemptAnonymous({ try acquisition.exact(revision, offline: offline) }), + pack.revision == revision + { + acquisition.remember(pack) + return try withAnonymousTree( + acquisition, pack: pack, selections: selections, historical: historical, + uncoveredSupport: uncoveredSupport, observingCoverage: observingCoverage, body) + } + guard !offline else { throw CoreError.notFound("cached Git commit \(revision) for \(id)") } + return try withMirrorLock(at: mirrorURL(sourceID: id)) { lock in + let mirror = try pinnedMirror( + sourceID: id, + source: .init(kind: source.kind, url: source.kind == .git ? source.gitURL : nil), + revision: revision, offline: false, lock: lock) + guard let result = try read(mirror, lock: lock) else { + throw CoreError.notFound("locked Git commit \(revision) for \(id)") + } + return result + } + } + package func storeArtifact(_ data: Data, digest: String) throws -> URL { guard "sha256:" + FileHash.sha256Hex(data: data) == digest else { throw CoreError.invalidState("artifact digest mismatch") @@ -893,26 +910,27 @@ package struct SourceCache { /// Makes exact Git objects durable before the caller's journal can reference the new ledger. /// A failed preparation leaves a cleanup marker; reconciliation keeps the committed closure. package func retain(references: RetentionReferences, offline: Bool = false) throws { - for (ordinal, pin) in references.git.sorted(by: { - ($0.source, $0.revision) < ($1.source, $1.revision) - }).enumerated() { - guard let location = references.sourceLocations[pin.source], Self.isObjectID(pin.revision) - else { + let groups = Dictionary(grouping: references.requiredGitObjects, by: \.source) + for (ordinal, identity) in groups.keys.sorted().enumerated() { + guard let location = references.sourceLocations[identity] else { throw CoreError.invalidState("missing exact retention coordinates") } - let kind: SourceKind = pin.source.hasPrefix("local:") ? .local : .git - let source = LockedSource( - kind: kind, url: kind == .git ? location : nil, - requirement: .revision(pin.revision)) - _ = try pinnedMirror( - sourceID: pin.source, source: source, revision: pin.revision, offline: offline) - let retained = SourceCache( - store: store, - checkpoint: { point in - try checkpoint("retention.\(ordinal)." + point) - }) - try retained.retainWatchRevision( - sourceID: pin.source, source: location, revision: pin.revision) + let kind: SourceKind = identity.hasPrefix("local:") ? .local : .git + let pins = groups[identity]!.map(\.revision).sorted() + let mirror = mirrorURL(sourceID: identity) + try withMirrorLock(at: mirror) { descriptor in + for revision in pins { + let source = LockedSource( + kind: kind, url: kind == .git ? location : nil, requirement: .revision(revision)) + _ = try pinnedMirror( + sourceID: identity, source: source, revision: revision, offline: offline, + lock: descriptor) + } + let retained = SourceCache( + store: store, checkpoint: { try checkpoint("retention.\(ordinal)." + $0) }) + try retained.retainWatchRevisions( + pins, at: mirror, source: location, descriptor: descriptor) + } } } @@ -947,35 +965,11 @@ package struct SourceCache { throw CoreError.invalidState("transaction recovery must precede pruning") } let cache = try scope.child("cache") - let transactionToUse = transaction - let paths = Set( - references.git.map { - materializedURL(sourceID: $0.source, revision: $0.revision).standardizedFileURL.path - }) let digests = Set(references.artifacts.map { String($0.dropFirst(7)) }) let edits = references.live func edited(_ url: URL) -> Bool { edits.contains { PathSafety.isContained($0, in: url) } - } - if try cache.info("materialized") != nil { - let materialized = try cache.child("materialized") - for name in try materialized.names() { - let source = try materialized.child(name) - let pins = try source.names() - var unused: [String] = [] - for pin in pins { - let tree = try source.child(pin) - if !paths.contains(tree.url.path) && !edited(tree.url) { unused.append(pin) } - } - let retainsDescendant = paths.contains { - PathSafety.isContained(URL(fileURLWithPath: $0), in: source.url) - } - if unused.count == pins.count && !retainsDescendant { - try transactionToUse.delete(materialized.url.appendingPathComponent(name)) - } else { - for pin in unused { try transactionToUse.delete(source.url.appendingPathComponent(pin)) } - } - } + || references.liveAliases.contains { PathSafety.isContained($0, in: url) } } for container in ["artifacts", "artifact-content"] where try cache.info(container) != nil { let directory = try cache.child(container) @@ -987,10 +981,28 @@ package struct SourceCache { throw CoreError.unsafePath("unexpected artifact cache entry") } if !digests.contains(name) && !edited(url) { - try transactionToUse.delete(url) + try transaction.delete(url) + } + } + } + } + + package func existingMaterializedPins() throws -> [URL] { + guard let scope = try store.openDirectoryIfPresent(), let cache = try scope.directory("cache"), + let materialized = try cache.directory("materialized") + else { return [] } + var result: [URL] = [] + for key in try materialized.names() { + let source = try materialized.child(key) + for revision in try source.names() { + let path = "state/cache/materialized/" + key + "/" + revision + guard TransactionPaths.isMaterializedPin(path) else { + throw CoreError.unsafePath("unexpected materialized pin: " + path) } + result.append(try source.child(revision).url) } } + return result } package func validatePath(_ url: URL, directory: Bool = true) throws { @@ -1200,6 +1212,10 @@ package struct SourceCache { mirror.deletingPathExtension().lastPathComponent + ".lock") return try FileLock.withExistingDescriptor(at: lock) { descriptor in try validatePath(mirror) + let directory = try DirectoryHandle(at: mirror) + guard let config = try directory.info("config"), config.st_mode & S_IFMT == S_IFREG else { + throw CoreError.unsafePath("mirror configuration must be a regular file") + } return try body(mirror, descriptor) } } @@ -1228,7 +1244,7 @@ package struct SourceCache { source = try git( mirror, ["config", "--get", "remote.origin.url"], operation: .readOrigin, source: "the cached source", lock: lock) - } catch let error as GitError where error.exitCode == 1 && error.stderr.isEmpty { + } catch let error as GitError where error.exitCode == 1 { throw CoreError.invalidState("cached Git source has no origin URL") } guard !source.isEmpty else { @@ -1247,18 +1263,4 @@ package struct SourceCache { + FileHash.sha256Hex(data: Data(sourceID.utf8)) } - /// Rejects a symbolic link that can lead outside the extracted tree. A dangling link that stays - /// inside, such as one to an uncommitted file, cannot be followed and is kept. - private func validateTree(_ tree: URL) throws { - guard let root = PathSafety.realPath(tree.path), - let enumerator = FileManager.default.enumerator( - at: tree, includingPropertiesForKeys: [.isSymbolicLinkKey]) - else { return } - for case let url as URL in enumerator - where try url.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { - guard try PathSafety.linkStaysInside(url, root: root) else { - throw CoreError.unsafePath("source symlink escapes committed tree") - } - } - } } diff --git a/Sources/AgentsCore/SourceResolutionSession.swift b/Sources/AgentsCore/SourceResolutionSession.swift index 728f8b4..b2e6b47 100644 --- a/Sources/AgentsCore/SourceResolutionSession.swift +++ b/Sources/AgentsCore/SourceResolutionSession.swift @@ -22,6 +22,14 @@ package final class SourceResolutionSession { private var archiveTrees: [PrivateSourceRecovery.Reference: URL] = [:] private var commits: [SourceSnapshotID: String] = [:] private var catalogs: [String: SourceCatalog] = [:] + private var localRepositoryChecks: [URL: Bool] = [:] + private var localCatalogs: [String: LocalGitCatalog] = [:] + private var expandedGit: [SourceSnapshotID: [GitTreeArchive.Selection: SourceSnapshot.Lookup]] = + [:] + private var expandedPaths: [SourceSnapshotID: GitTreeArchive.Coverage] = [:] + private var expandedSubtrees: [SourceSnapshotID: Set] = [:] + private var retainedPins: [RetentionReferences.Git: LedgerGitPin] = [:] + private var verifiedRetainedPins = Set() private var advertisements: [String: GitAcquisition.Advertisement] = [:] private var observedSelections: [SourceSnapshotID: Set] = [:] private var exact: [SourceSnapshotID: SourceSnapshot] = [:] @@ -90,6 +98,13 @@ package final class SourceResolutionSession { closed = true snapshots.removeAll() exact.removeAll() + expandedGit.removeAll() + localRepositoryChecks.removeAll() + expandedPaths.removeAll() + expandedSubtrees.removeAll() + retainedPins.removeAll() + verifiedRetainedPins.removeAll() + localCatalogs.removeAll() localTrees.removeAll() borrowed.removeAll() evidence.removeAll() @@ -153,7 +168,9 @@ package final class SourceResolutionSession { return Set(selected).count == 1 ? [SourceRevision(revision: selected[0])] : [] } if catalogs[id] == nil { - if let acquisition = cache.anonymousAcquisition(source), + if source.kind == .local, try isGitSource(source) { + catalogs[id] = try localCatalog(source, identity: id, spending: spending).catalog + } else if let acquisition = cache.anonymousAcquisition(source), let advertisement = try cache.attemptAnonymous({ try acquisition.discover() }), remoteResolves(requirements, in: advertisement.catalog) { @@ -189,6 +206,17 @@ package final class SourceResolutionSession { catalog.references[expression] = GitAcquisition.reference( expression, in: advertisement.catalog)?.1 + } else if let local = localCatalogs[id] { + if local.resolvesInAdvertisement(expression) { + catalog.references[expression] = try local.revision(expression) + } else { + catalog.references[expression] = try local.transportRevision( + expression, source: source.localURL(environment: store.environment), + workspace: workspace, spending: spending) + } + if let revision = catalog.references[expression] { + commits[.init(source: id, revision: revision)] = revision + } } else { catalog.references[expression] = try temporaryCache.catalogRevision( expression, source: source) @@ -197,6 +225,14 @@ package final class SourceResolutionSession { } catalogs[id] = catalog let selected = try catalog.candidates(requirements: requirements, spending: spending) + if let local = localCatalogs[id] { + let unchecked = Set( + selected.map(\.revision).filter { + commits[.init(source: id, revision: $0)] != $0 + }) + try local.validateCommits(unchecked, in: workspace) + for revision in unchecked { commits[.init(source: id, revision: revision)] = revision } + } if let advertisement = advertisements[id] { for pin in selected { let availableTags = advertisement.catalog.tags.filter { $0.value == pin.revision } @@ -302,49 +338,30 @@ package final class SourceResolutionSession { route: route, request: request, offline: offline) } let source = declaringSource(source) + let identity = try source.identity(environment: store.environment) var pin = pin - pin.revision = try commit(pin.revision, source: source) - let id = try source.identity(environment: store.environment) - let key = SourceSnapshotID(source: id, revision: pin.revision) - let base: SourceSnapshot + if !offline { pin.revision = try commit(pin.revision, source: source) } + let key = SourceSnapshotID(source: identity, revision: pin.revision) + let root: URL if let existing = exact[key] { - base = existing + root = existing.root } else { - var selected = source - selected.requirement = .revision(pin.revision) - selected.path = nil - func copy(_ tree: URL) throws -> SourceSnapshot { - let root = workspace.appendingPathComponent(UUID().uuidString) - try FileManager.default.copyItem(at: tree, to: root) - return try SourceSnapshot( - snapshot: key, pin: pin, root: root, - localEnvironment: localEnvironment(for: source), - liveRoot: source.kind == .local && source.requirement == nil - ? source.localURL(environment: store.environment) : nil) - } - let available: SourceCache? - if try temporaryCache.catalogRevision(pin.revision, source: selected) == pin.revision { - available = temporaryCache - } else if try objectCache.catalogRevision(pin.revision, source: selected) == pin.revision { - available = objectCache - } else { - available = nil - } - if let available { - base = try available.withSnapshot( - sourceID: id, - source: LockedSource( - kind: selected.kind, url: selected.kind == .git ? selected.gitURL : nil, - requirement: selected.requirement), revision: pin.revision, copy) - } else { - base = try cache.withResolvedSnapshot(selected, cacheSource: false) { resolved, tree in - guard resolved.revision == pin.revision else { - throw CoreError.invalidState("resolved snapshot differs from its commit pin") - } - return try copy(tree) - } + root = workspace.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileSystem.createDirectory(at: root) + let view = try SourceSnapshot(snapshot: key, pin: pin, root: root) { + [weak self] path, recursive, followsLinks, optional in + guard let self else { throw CoreError.invalidState("source session is closed") } + return try self.expandGit( + .init(path: path, recursive: recursive, followsLinks: followsLinks, optional: optional), + key: key, source: source, in: root, offline: offline) } - if let refs = observedSelections[key], let advertisement = advertisements[id], + exact[key] = view + register( + view, + source: LockedSource( + kind: source.kind, url: source.kind == .git ? source.gitURL : nil, + requirement: .revision(pin.revision))) + if let refs = observedSelections[key], let advertisement = advertisements[identity], let acquisition = cache.anonymousAcquisition(source), let pack = try acquisition.exact(pin.revision, offline: true) { @@ -352,20 +369,243 @@ package final class SourceResolutionSession { acquisition.note(ref, pack: pack, observedAt: advertisement.time) } } - exact[key] = base - register( - base, - source: LockedSource( - kind: source.kind, - url: source.kind == .git ? source.gitURL : nil, requirement: .revision(pin.revision))) - try Task.checkCancellation() } return try SourceSnapshot( - snapshot: key, pin: pin, root: base.root, - discoveryPath: source.path ?? ".", + snapshot: key, pin: pin, root: root, discoveryPath: source.path ?? ".", localEnvironment: localEnvironment(for: source), liveRoot: source.kind == .local && source.requirement == nil - ? source.localURL(environment: store.environment) : nil) + ? source.localURL(environment: store.environment) : nil, + expand: exact[key]?.expand) + } + + package func borrowedGitTree(_ pin: LedgerGitPin) throws -> URL? { + let key = SourceSnapshotID(source: pin.key.source, revision: pin.key.revision) + guard let view = exact[key] else { return nil } + for request in pin.selection { + _ = try view.resource( + request.path, recursive: request.recursive, followsLinks: request.followsLinks) + } + return view.root + } + + package func preservingRetainedGit(in ledger: ResolvedLedger, roots: [String: URL]) throws { + retainedPins = try LedgerGitPin.collect(ledger, roots: roots) + } + + /// One exact archive selection serves all requested resources of a locked pin. + package func lockedGitTree( + _ pin: LedgerGitPin, offline: Bool, historical: Bool = false + ) throws -> URL { + try lockedGitTree( + pin, selections: pin.selection, uncoveredSupport: pin.uncoveredSupportPaths(), + offline: offline, historical: historical) + } + + /// A retained pin can prove historical support through another selected resource's hash. + package func verifyRetainedGitTree(_ pin: LedgerGitPin, in root: URL, offline: Bool) throws { + let uncovered = try pin.uncoveredSupportPaths() + let selections = pin.selection.filter { + !$0.recursive && uncovered.contains(Data($0.path.utf8)) + } + let canonical = + try selections.isEmpty + ? nil + : lockedGitTree(pin, selections: selections, uncoveredSupport: uncovered, offline: offline) + for resource in pin.resources.values.sorted(by: { $0.path < $1.path }) { + try pin.verify( + resource, in: root, authenticatingSupportFrom: canonical, uncoveredSupport: uncovered) + } + } + + private func lockedGitTree( + _ pin: LedgerGitPin, selections: [GitTreeArchive.Selection], uncoveredSupport: Set, + offline: Bool, historical: Bool = false + ) throws -> URL { + try requireOpen() + let root = workspace.appendingPathComponent(UUID().uuidString, isDirectory: true) + func take(_ tree: URL) throws -> URL { + try FileManager.default.moveItem(at: tree, to: root) + return root + } + do { + return try cache.withGitSelection( + pin.source, revision: pin.key.revision, selections: selections, offline: true, + historical: historical, uncoveredSupport: uncoveredSupport, take) + } catch CoreError.notFound where !offline { + return try objectCache.withGitSelection( + declaringSource(pin.source), revision: pin.key.revision, selections: selections, + offline: false, historical: historical, uncoveredSupport: uncoveredSupport, take) + } catch CoreError.notFound where pin.firstSupportFile != nil { + throw CoreError.invalidState( + "unverifiable locked Git support at \(pin.key.source) \(pin.key.revision)/\(pin.firstSupportFile!)" + ) + } + } + + private func expandGit( + _ selection: GitTreeArchive.Selection, key: SourceSnapshotID, source: SourceDeclaration, + in root: URL, offline: Bool + ) throws -> SourceSnapshot.Lookup { + try requireOpen() + let exactPin = RetentionReferences.Git(source: key.source, revision: key.revision) + if let prior = retainedPins[exactPin], !verifiedRetainedPins.contains(exactPin) { + if let existing = try cache.existingPinnedTree(sourceID: key.source, revision: key.revision) { + try verifyRetainedGitTree(prior, in: existing, offline: offline) + } + verifiedRetainedPins.insert(exactPin) + } + if let lookup = expandedGit[key]?[selection] { return lookup } + if expandedSubtrees[key, default: []].contains(where: { + $0 == "." || selection.path.utf8.elementsEqual($0.utf8) + || selection.path.utf8.starts(with: ($0 + "/").utf8) + }), + let lookup = try Self.coveredAvailability( + selection, in: root, coverage: expandedPaths[key, default: .init()]) + { + return lookup + } + // The two disposable caches may already own the exact objects behind a frozen selection. + let available: SourceCache + if try temporaryCache.catalogRevision(key.revision, source: source) == key.revision { + available = temporaryCache + } else if try objectCache.catalogRevision(key.revision, source: source) == key.revision { + available = objectCache + } else { + available = cache + } + var coverage = GitTreeArchive.Coverage() + try available.withGitSelection( + source, revision: key.revision, selections: [selection], offline: true, + observingCoverage: { coverage = $0 }, + { tree in + let source = try DirectoryHandle(at: tree) + let destination = try DirectoryHandle(at: root) + try Self.mergeGitTree(source, into: destination, adding: false) + try Self.mergeGitTree(source, into: destination, adding: true) + // Recursive extraction checks nested links under either policy. Only a plain + // directory path can stand as coverage for future requests. + if selection.recursive, + try Self.coveredAvailability(selection, in: tree, coverage: coverage, directoryOnly: true) + == .available + { + expandedSubtrees[key, default: []].insert(selection.path) + } + } + ) + expandedPaths[key, default: .init()].entries.formUnion(coverage.entries) + expandedPaths[key, default: .init()].links.formUnion(coverage.links) + expandedPaths[key, default: .init()].gitlinks.formUnion(coverage.gitlinks) + expandedPaths[key, default: .init()].omittedDirectories.formUnion(coverage.omittedDirectories) + let lookup = + selection.optional ? coverage.optionalSelections[selection] ?? .spellingMiss : .available + expandedGit[key, default: [:]][selection] = lookup + return lookup + } + + /// A nil result requires an exact tree walk. + private static func coveredAvailability( + _ selection: GitTreeArchive.Selection, in root: URL, coverage: GitTreeArchive.Coverage, + directoryOnly: Bool = false + ) throws -> SourceSnapshot.Lookup? { + var parent = try DirectoryHandle(at: root) + var components = selection.path.utf8.split(separator: 47)[...] + var path = Data() + while let part = components.popFirst() { + if part.elementsEqual(".".utf8) { continue } + let name = String(decoding: part, as: UTF8.self) + if !path.isEmpty { path.append(47) } + path.append(contentsOf: part) + let exact = coverage.entries.contains(path) + let info = try exact ? parent.info(name) : nil + if coverage.links.contains(path) || (info?.st_mode ?? 0) & S_IFMT == S_IFLNK { + if !selection.followsLinks { + throw CoreError.unsafePath( + "Git input is a link: " + String(decoding: path, as: UTF8.self)) + } + // A dangling link and a missing ordinary suffix have different admission rules. + return nil + } + guard let info else { + // A scoped request can materialize a directory omitted from a recursive archive. + if components.isEmpty, selection.optional, !directoryOnly, + !coverage.omittedDirectories.contains(path) + { + return .spellingMiss + } + return nil + } + if coverage.gitlinks.contains(path) { + // Tar represents gitlinks as directories. The committed entry is not traversable. + return components.isEmpty && !directoryOnly ? .available : nil + } + let kind = info.st_mode & S_IFMT + if components.isEmpty { return !directoryOnly || kind == S_IFDIR ? .available : nil } + guard kind == S_IFDIR else { return nil } + parent = try parent.child(name, matching: info) + } + return .available + } + + private static func mergeGitTree( + _ source: DirectoryHandle, into destination: DirectoryHandle, adding: Bool + ) throws { + var names = Set(try destination.names().map { Data($0.utf8) }) + for name in try source.names() { + guard let incoming = try source.info(name) else { + throw CoreError.invalidState("archive entry disappeared: " + name) + } + if let current = try destination.info(name) { + guard names.contains(Data(name.utf8)), + current.st_mode & S_IFMT == incoming.st_mode & S_IFMT + else { throw CoreError.invalidState("conflicting archive entry: " + name) } + if incoming.st_mode & S_IFMT == S_IFDIR { + try mergeGitTree( + source.child(name, matching: incoming), + into: destination.child(name, matching: current), + adding: adding) + } else if !adding { + guard let a = try FileSnapshot.read(name, from: source), + let b = try FileSnapshot.read(name, from: destination), + a.digest == b.digest, a.executable == b.executable + else { throw CoreError.invalidState("conflicting archive bytes: " + name) } + } + } else if adding { + try destination.copy(name, from: source, named: name, durable: false) { _ in + try Task.checkCancellation() + } + names.insert(Data(name.utf8)) + } + } + } + + private func localCatalog( + _ source: SourceDeclaration, identity: String, spending: (Int) throws -> Void = { _ in } + ) throws -> LocalGitCatalog { + if let captured = localCatalogs[identity] { return captured } + let captured = try LocalGitCatalog( + source: source.localURL(environment: store.environment), workspace: workspace, + spending: spending) + localCatalogs[identity] = captured + return captured + } + + func inspectLocalRevision(_ source: SourceDeclaration) throws -> SourceRevision { + if let pin = try candidates(for: source, requirements: [source.requirement]).first { + return pin + } + let local = try localCatalog(source, identity: source.identity(environment: store.environment)) + let ref = try SourceReference( + requirement: source.requirement, tags: Array(local.catalog.tags.keys)) + let arguments = ["rev-parse", "--verify", "--end-of-options", ref.name + "^{commit}"] + let output = try ProcessRunner.isolatedGit(arguments, in: local.repository) + // Alternate objects may explain a missing ref, but cannot extend the advertisement. + guard output.exitCode != 0 else { + throw CoreError.notFound("source reference is not advertised: " + ref.name) + } + throw GitError( + operation: .resolveRevision(revision: ref.name), source: source.location, + stderr: output.stderr, command: ["git"] + arguments, exitCode: output.exitCode, + replacingPaths: [local.repository, workspace]) } private func commit(_ object: String, source: SourceDeclaration) throws -> String { @@ -384,6 +624,12 @@ package final class SourceResolutionSession { resolved = pack.revision } else if let cached = try cache.catalogRevision(object, source: source) { resolved = cached + } else if source.kind == .local, try isGitSource(source) { + let local = try localCatalog(source, identity: key.source) + guard let admitted = try local.admittedCommit(object) else { + throw CoreError.notFound("Git object is outside the advertised closure: " + object) + } + resolved = admitted } else if let frozen = try temporaryCache.catalogRevision(object, source: source) { resolved = frozen } else { @@ -591,16 +837,10 @@ package final class SourceResolutionSession { guard source.kind == .local else { return source.kind == .git } let local = source.localURL(environment: store.environment) if BundleSourceLocation.container(of: local, in: store) != nil { return false } - // Validate this directory's metadata, including worktree gitfiles, without ancestor discovery. - for path in [".git", "."] { - if (try? ProcessRunner.git( - ["--no-optional-locks", "-C", local.path, "rev-parse", "--resolve-git-dir", path], - operation: .findRepositoryRoot, source: source.location)) != nil - { - return true - } - } - return false + if let checked = localRepositoryChecks[local] { return checked } + let checked = try SourceCache.isLocalRepository(local) + localRepositoryChecks[local] = checked + return checked } private func localEnvironment(for source: SourceDeclaration) -> SourceEnvironment? { @@ -638,6 +878,15 @@ package final class SourceResolutionSession { { return try body(snapshot.pin, snapshot.root) } + if source.kind == .local, try isGitSource(source) { + guard let first = try candidates(for: source, requirements: [source.requirement]).first else { + throw CoreError.notFound("Git source has no matching revision: " + source.location) + } + let view = try snapshot(source, at: first) + _ = try view.directory() + snapshots.append(.init(identity: identity, source: effective, pin: first, root: view.root)) + return try body(first, view.root) + } let snapshot = try cache.withResolvedSnapshot(source, cacheSource: mode == .persistentCache) { pin, tree in let root = workspace.appendingPathComponent(UUID().uuidString) diff --git a/Sources/AgentsCore/SourceRevisionInspection.swift b/Sources/AgentsCore/SourceRevisionInspection.swift index b783a07..4be224f 100644 --- a/Sources/AgentsCore/SourceRevisionInspection.swift +++ b/Sources/AgentsCore/SourceRevisionInspection.swift @@ -8,28 +8,18 @@ extension SourceCache { if case .archive = route { return try withResolvedSnapshot(source, cacheSource: false) { pin, _ in pin } } - let id = try source.identity(environment: store.environment) try source.requirement?.validate() guard source.kind != .wellKnown else { throw CoreError.invalidSource("well-known sources have no Git revisions") } if source.kind == .local { - let root = source.localURL(environment: store.environment) - func git(_ arguments: [String], operation: GitError.Operation) throws -> String { - try ProcessRunner.git( - ["--no-optional-locks", "-C", root.path] + arguments, - operation: operation, source: source.location - ).stdout.trimmingCharacters(in: .whitespacesAndNewlines) + return try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: sourcePolicy, requireRecordedTransport: requireRecordedTransport + ) { session in + try session.inspectLocalRevision(source) } - let tags = try git(["tag", "--list"], operation: .listTags).split(separator: "\n").map( - String.init) - let ref = try SourceReference(requirement: source.requirement, tags: tags) - return try SourceRevision( - revision: git( - ["rev-parse", "--verify", ref.name + "^{commit}"], - operation: .resolveRevision(revision: ref.name)), - version: ref.version) } + let id = try source.identity(environment: store.environment) func cachedCommit(_ object: String) throws -> String? { try? inspectCommit(object, sourceID: id, source: source.location) } @@ -78,6 +68,8 @@ extension SourceCache { } package static func isObjectID(_ value: String) -> Bool { - value.range(of: #"^[0-9a-f]{40}([0-9a-f]{24})?$"#, options: .regularExpression) != nil + let bytes = value.utf8 + return (bytes.count == 40 || bytes.count == 64) + && bytes.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } } } diff --git a/Sources/AgentsCore/SourceSnapshot.swift b/Sources/AgentsCore/SourceSnapshot.swift index 28da20b..9d13f59 100644 --- a/Sources/AgentsCore/SourceSnapshot.swift +++ b/Sources/AgentsCore/SourceSnapshot.swift @@ -14,6 +14,12 @@ package struct SourceSnapshotID: Hashable, Sendable { /// A borrowed view, valid only while its source session is open. Stable output uses `snapshot` /// and relative paths. `liveRoot` exists only for actual local authoring sources. package struct SourceSnapshot { + package enum Lookup: Equatable { + case available + case spellingMiss + case omittedTarget + } + package let snapshot: SourceSnapshotID package let pin: SourceRevision? package let root: URL @@ -23,11 +29,12 @@ package struct SourceSnapshot { package let localEnvironment: SourceEnvironment? package let liveRoot: URL? package let packageIdentity: String + package let expand: ((String, Bool, Bool, Bool) throws -> Lookup)? package init( snapshot: SourceSnapshotID, pin: SourceRevision?, root: URL, discoveryPath: String = ".", localEnvironment: SourceEnvironment? = nil, liveRoot: URL? = nil, - packageIdentity: String? = nil + packageIdentity: String? = nil, expand: ((String, Bool, Bool, Bool) throws -> Lookup)? = nil ) throws { self.snapshot = snapshot self.packageIdentity = packageIdentity ?? snapshot.source @@ -36,13 +43,52 @@ package struct SourceSnapshot { self.discoveryPath = try PathSafety.sanitizeSubpath(discoveryPath) self.localEnvironment = localEnvironment self.liveRoot = liveRoot - _ = try directory() + self.expand = expand + _ = try directory(requiringContents: false) + } + + package func directory(requiringContents: Bool = true) throws -> URL { + if requiringContents { return try resource(discoveryPath, recursive: true, optional: true) } + return try checkedResource(discoveryPath) } - package func directory() throws -> URL { try resource(discoveryPath) } + package func discoveryResource( + _ path: String, recursive: Bool, followsLinks: Bool = true, optional: Bool = false + ) throws -> URL { + let relative = + discoveryPath == "." ? path : path == "." ? discoveryPath : discoveryPath + "/" + path + return try resource( + relative, recursive: recursive, followsLinks: followsLinks, optional: optional) + } /// Both authored spelling and real symlink resolution must remain in the snapshot. - package func resource(_ path: String) throws -> URL { + package func resource( + _ path: String, recursive: Bool? = nil, followsLinks: Bool = true, optional: Bool = false + ) throws -> URL { + let file = try checkedResource(path) + if path != "." || recursive == true, let expand { + let safe = try PathSafety.sanitizeSubpath(path) + switch try expand(safe, recursive ?? true, followsLinks, optional) { + case .available: + break + case .spellingMiss: + // A byte-exact Git miss can still name an existing file on a folding filesystem. + var info = stat() + if lstat(file.path, &info) == 0 { + throw CoreError.unsafePath("Git input spelling collides with a snapshot entry: " + safe) + } + case .omittedTarget: + // The link can be present while its target remains absent from the snapshot. + if FileManager.default.fileExists(atPath: file.path) { + throw CoreError.unsafePath("Git link resolves despite an archive-omitted target: " + safe) + } + } + return try checkedResource(path) + } + return file + } + + private func checkedResource(_ path: String) throws -> URL { guard !path.hasPrefix("~") else { throw CoreError.unsafePath("resource must be relative") } let file = try PathSafety.resolvedChild(base: root, subpath: path) guard PathSafety.isContained(file.resolvingSymlinksInPath(), in: root.resolvingSymlinksInPath()) @@ -68,8 +114,16 @@ package struct SourceSnapshot { } package func relativePath(_ url: URL) throws -> String { - let path = PathSafety.relativePath(url.path, to: root.path) - _ = try resource(path) + var path = PathSafety.relativePath(url.path, to: root.path) + // Enumeration can report a dangling link under the physical spelling of the root. + if path == ".." || path.hasPrefix("../"), let physical = PathSafety.realPath(root.path) { + let prefix = (physical + "/").utf8 + let spelling = url.path.utf8 + if spelling.starts(with: prefix) { + path = String(decoding: spelling.dropFirst(prefix.count), as: UTF8.self) + } + } + _ = try checkedResource(path) return path } } diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index dc9444b..17e0ed9 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -15,6 +15,10 @@ public struct StateStore: Sendable { ? environment.projectDirectory.appendingPathComponent(".agent") : environment.homeDirectory.appendingPathComponent(".agents") } + var physicalDirectory: URL { + let base = scope == .project ? environment.projectDirectory : environment.homeDirectory + return base.resolvingSymlinksInPath().appendingPathComponent(directory.lastPathComponent) + } public var declarationURL: URL { directory.appendingPathComponent(Self.declarationFileName) } public var resolvedURL: URL { directory.appendingPathComponent(Self.resolvedFileName) } public var watchURL: URL { directory.appendingPathComponent(Self.watchFileName) } @@ -120,9 +124,6 @@ public struct StateStore: Sendable { _ = try readLedger() _ = try readWatch() } - let base = scope == .project ? environment.projectDirectory : environment.homeDirectory - let physicalDirectory = base.resolvingSymlinksInPath().appendingPathComponent( - directory.lastPathComponent) func locked(_ body: (Int32) throws -> T) throws -> T { if let context = TransactionLockContext.current(self), let root = context.projectRootDirectory diff --git a/Sources/AgentsCore/TransactionDisposal.swift b/Sources/AgentsCore/TransactionDisposal.swift index 15072ec..135e948 100644 --- a/Sources/AgentsCore/TransactionDisposal.swift +++ b/Sources/AgentsCore/TransactionDisposal.swift @@ -1,11 +1,116 @@ import Foundation extension TransactionSession { + /// Admission uses the sealed generations and the same container grouping as recovery. + func admitDisposal(journalLimits: LedgerLimits = .standard) throws { + let groups = Dictionary(grouping: journal.entries.indices) { journal.entries[$0].container } + let standard = LedgerLimits.standard + // The ready journal already passed standard admission. A node takes at least one + // byte. The disposal graph adds at most four JSON levels per filesystem level, + // and the existing capture bound includes the new container level. + var remaining = + max(0, min(journalLimits.encodedBytes, journalLimits.nodes)) - persistedByteCount + let standardStructure = + journalLimits.depth >= standard.depth && journalLimits.objectBytes >= standard.objectBytes + && journalLimits.entries >= standard.entries && journalLimits.keyBytes >= standard.keyBytes + func charge(_ bytes: Int) { + if remaining >= 0 { remaining = bytes <= remaining ? remaining - bytes : -1 } + } + charge(16) // The longest phase plus a newline. + for (containerIndex, record) in journal.containers.enumerated() { + let handle = try container(containerIndex) + var size = FileSnapshot.CaptureSize(entries: 1, bytes: record.name.utf8.count) + var readyNames: [String] = [] + var staged = false + // A snapshot has at most 20 lines per member, including its wrapper and + // identity. 8 KiB covers those lines at up to 128 levels of indentation, + // fixed fields, and their separators. Names can expand to six bytes per byte. + charge(8_192) + for index in groups[containerIndex, default: []] { + let entry = journal.entries[index] + charge( + 1_024 + 6 + * (TransactionJournal.Conflict.reasonBytes + entry.path.utf8.count + + containerLocation(index).utf8.count)) + if entry.progress == .skipped { continue } + staged = true + let staging = TransactionSlot.staging(for: entry) + let displaced: TransactionSlot = entry.action == .delete ? .deleted : .exchanged + var old = preimageSizes[index, default: .init()] + var new = stagedSizes[index, default: .init()] + if entry.preimage != nil { + old.bytes += displaced.name(index).utf8.count - entry.name.utf8.count + old.depth += 1 + } + if entry.staged != nil { + readyNames.append(staging.name(index)) + let rollbackSlot = entry.preimage == nil ? TransactionSlot.withdrawn : staging + new.bytes += max(0, rollbackSlot.name(index).utf8.count - staging.name(index).utf8.count) + new.depth += 1 + } + size.entries += max(old.entries, new.entries) + size.bytes += max(old.bytes, new.bytes) + size.depth = max(size.depth, old.depth, new.depth) + try size.validate() + charge(8_192 * (old.entries + new.entries) + 6 * (old.bytes + new.bytes)) + } + guard try handle.names() == readyNames.sorted() else { + throw conflict(record.entry, "unexpected work or probe before publication") + } + // A container whose deferred entries were all skipped has no stage barrier. + if !staged { try handle.sync() } + } + if standardStructure, persistedByteCount > 0, remaining >= 0 { return } + + var upper = journal + upper.phase = .rolledBack + let reason = String(repeating: "\u{0}", count: TransactionJournal.Conflict.reasonBytes) + for (containerIndex, record) in journal.containers.enumerated() { + var members: [FileSnapshot.Member] = [] + for index in groups[containerIndex, default: []] { + let entry = journal.entries[index] + upper.entries[index].conflict = .init( + reason: reason, + locations: [ + entry.path, containerLocation(index), + ]) + if entry.progress == .skipped { continue } + let staging = TransactionSlot.staging(for: entry) + let displaced: TransactionSlot = entry.action == .delete ? .deleted : .exchanged + if let snapshot = entry.preimage { + members.append(.init(name: displaced.name(index), snapshot: snapshot)) + } + if let snapshot = entry.staged { + let rollbackSlot = entry.preimage == nil ? TransactionSlot.withdrawn : staging + members.append(.init(name: rollbackSlot.name(index), snapshot: snapshot)) + } + upper.entries[index].progress = .publishing + } + upper.containers[containerIndex].disposal = .init( + identity: record.identity!, digest: String(repeating: "0", count: 64), + executable: false, mode: 0o700, children: members) + } + try LedgerAdmission.check(StateStore.encode(upper), limits: journalLimits) + } + + private func streamingDisposalMembers(_ container: Int) -> [String: FileObjectIdentity] { + var result: [String: FileObjectIdentity] = [:] + for (index, entry) in journal.entries.enumerated() where entry.container == container { + guard let identity = entry.streamingPreimage else { continue } + for layout in TransactionLayout.expected(entry) { + for (slot, member) in layout.objects where member.identity == identity { + result[slot.name(index)] = identity + } + } + } + return result + } + /// Verifies every expected distribution and seals disposal evidence for containers that /// hold user data. A failure is recorded on the entry or container that caused it. - func sealDisposal() throws { + func sealDisposal(rollingBack: Bool = false) throws { let layouts = try journal.entries.indices.map { index in - do { return try distribution(index) } catch { + do { return try distribution(index, rollingBack: rollingBack) } catch { try recordConflict(index, error) throw error } @@ -38,7 +143,8 @@ extension TransactionSession { journal.containers[index].disposal = nil return } - let snapshot = try FileSnapshot.read(record.name, from: parents[record.entry]) + let snapshot = try FileSnapshot.read( + record.name, from: parents[record.entry], streamingChildren: streamingDisposalMembers(index)) guard try handle.objectIdentity == snapshot?.identity else { throw conflict(record.entry, "container changed while sealing disposal") } @@ -79,14 +185,21 @@ extension TransactionSession { /// Commit disposes directly: `sealDisposal` verified the distribution and sealed this /// evidence immediately before the terminal marker. Deletion still verifies every object. - func dispose() throws { + func dispose(checkingComplete: Bool = false) throws { try requireScope() if !journal.disposing { + // A checkpoint can interrupt or change the tree after sealing. Admit complete + // evidence before enabling partial removal, then let the deleter check each object. + if checkingComplete { + for index in journal.containers.indices { try validateContainerForDisposal(index) } + } journal.disposing = true try persist(.disposing) try emit(.disposalIntent) } - for index in journal.containers.indices { try disposeContainer(index) } + for index in journal.containers.indices { + try disposeContainer(index) + } try requireScope() journal.finalized = true try persist(.finalized) @@ -103,11 +216,15 @@ extension TransactionSession { func verifyTarget(_ index: Int) throws { let entry = journal.entries[index] try requireParent(index) - if case .object(let expected) = TransactionLayout.expected(entry)[0].target { + let target = TransactionLayout.expected( + entry, checkingSkippedPreimage: journal.phase == .committed)[0].target + if case .object(let expected) = target { try entry.security.validateObject(expected, named: entry.name, in: parents[index]) } // Terminal phases have a single distribution; disposal may have removed its slots. - guard try TransactionLayout.expected(entry)[0].target.matches(entry.name, from: parents[index]) + guard + try target.matches( + entry.name, from: parents[index], streamingPreimage: entry.streamingPreimage) else { throw conflict( index, @@ -132,7 +249,7 @@ extension TransactionSession { } return } - guard FileObjectIdentity(actual) == identity else { + guard FileObjectIdentity(actual) == identity, actual.st_mode & 0o7777 == 0o700 else { throw conflict(record.entry, "private container identity changed") } if journal.entries.contains(where: { $0.container == index && $0.security.isPrivate }) { @@ -160,7 +277,8 @@ extension TransactionSession { } } if let expected = record.disposal { - let current = try FileSnapshot.read(record.name, from: parent) + let current = try FileSnapshot.read( + record.name, from: parent, streamingChildren: streamingDisposalMembers(index)) let matches = journal.disposing ? current.map(expected.containsRemaining) == true : current == expected @@ -175,7 +293,10 @@ extension TransactionSession { try requireParent(record.entry) try validateContainerForDisposal(index) if let identity = record.identity { - try parent.remove(record.name, expecting: record.disposal, identity: identity) { point in + try parent.remove( + record.name, expecting: record.disposal, identity: identity, + streamingChildren: streamingDisposalMembers(index) + ) { point in try emit( point.step == .synced ? .containerRemoved(index) : .unlinked(container: index, path: point.path)) diff --git a/Sources/AgentsCore/TransactionEvidence.swift b/Sources/AgentsCore/TransactionEvidence.swift index 214eaab..c82f531 100644 --- a/Sources/AgentsCore/TransactionEvidence.swift +++ b/Sources/AgentsCore/TransactionEvidence.swift @@ -1,3 +1,4 @@ +import Crypto import Foundation package struct FileObjectIdentity: Codable, Hashable, Sendable { @@ -34,6 +35,8 @@ struct DirectoryWriteLease: Equatable { /// Content and physical ownership are separate evidence. Descendant identities let /// terminal disposal resume after partial deletion without adopting new entries. struct FileSnapshot: Codable, Equatable, Sendable { + @TaskLocal static var captureLimits = LedgerLimits.standard + let identity: FileObjectIdentity let digest: String let executable: Bool @@ -54,13 +57,17 @@ struct FileSnapshot: Codable, Equatable, Sendable { } static func read(at url: URL) throws -> FileSnapshot? { + try measure(at: url).0 + } + + static func measure(at url: URL) throws -> (FileSnapshot?, CaptureSize) { var info = stat() if lstat(url.path, &info) != 0 { - if errno == ENOENT { return nil } + if errno == ENOENT { return (nil, .init()) } throw FileSystem.posixError(errno, at: url, otherwise: .unsafePath("cannot inspect target")) } let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) - return try read(url.lastPathComponent, from: parent) + return try measure(url.lastPathComponent, from: parent) } struct Capture { @@ -68,6 +75,7 @@ struct FileSnapshot: Codable, Equatable, Sendable { let contentHash: String let executableFlags: [String: Bool] let bytes: Data? + let size: CaptureSize } static func captureFile(at url: URL, maximumFileBytes: Int? = nil) throws -> Capture { @@ -75,7 +83,8 @@ struct FileSnapshot: Codable, Equatable, Sendable { if lstat(url.path, &info) != 0 { if errno == ENOENT { return Capture( - snapshot: nil, contentHash: FileHash.hashRecords([]), executableFlags: [:], bytes: nil) + snapshot: nil, contentHash: FileHash.hashRecords([]), executableFlags: [:], bytes: nil, + size: .init()) } throw FileSystem.posixError(errno, at: url, otherwise: .unsafePath("cannot inspect target")) } @@ -115,12 +124,25 @@ struct FileSnapshot: Codable, Equatable, Sendable { return Capture( snapshot: value, contentHash: value?.isRegular == true ? value!.digest : FileHash.hashRecords(records), - executableFlags: flags, bytes: rootBytes) + executableFlags: flags, bytes: rootBytes, size: budget.size) + } + + static func read( + _ name: String, from parent: DirectoryHandle, streaming identity: FileObjectIdentity? = nil, + streamingChildren: [String: FileObjectIdentity] = [:] + ) throws -> FileSnapshot? { + try measure(name, from: parent, streaming: identity, streamingChildren: streamingChildren).0 } - static func read(_ name: String, from parent: DirectoryHandle) throws -> FileSnapshot? { + static func measure( + _ name: String, from parent: DirectoryHandle, streaming identity: FileObjectIdentity? = nil, + streamingChildren: [String: FileObjectIdentity] = [:] + ) throws -> (FileSnapshot?, CaptureSize) { var budget = CaptureBudget() - return try read(name, from: parent, relative: "", budget: &budget, collect: nil) + let snapshot = try read( + name, from: parent, relative: "", budget: &budget, streamingIdentity: identity, + streamingChildren: streamingChildren, collect: nil) + return (snapshot, budget.size) } static func capturePortableTree( @@ -169,58 +191,78 @@ struct FileSnapshot: Codable, Equatable, Sendable { return (entries.sorted { $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) }, objects) } + struct CaptureSize: Sendable { + var entries = 0 + var bytes = 0 + var depth = 0 + + func validate(limits: LedgerLimits = FileSnapshot.captureLimits) throws { + guard entries <= limits.entries, bytes <= limits.resourceBytes, depth < limits.depth / 4 + else { throw CoreError.invalidState("transaction tree exceeds resource limits") } + } + } + private struct CaptureBudget { let maximumFileBytes: Int? let limits: LedgerLimits let recursive: Bool - var entries = 0 - var bytes = 0 + var size = CaptureSize() init( - maximumFileBytes: Int? = nil, limits: LedgerLimits = .standard, recursive: Bool = true + maximumFileBytes: Int? = nil, limits: LedgerLimits = FileSnapshot.captureLimits, + recursive: Bool = true ) { self.maximumFileBytes = maximumFileBytes self.limits = limits self.recursive = recursive } - mutating func consume(_ name: String, info: stat, depth: Int) throws { - entries += 1 - let size = info.st_mode & S_IFMT == S_IFREG ? info.st_size : 0 - guard entries <= limits.entries, depth < limits.depth / 4, - size >= 0, size <= limits.resourceBytes - bytes, - name.utf8.count <= limits.resourceBytes - bytes - Int(size) + mutating func consume(_ name: String, info: stat, depth: Int, streaming: Bool) throws { + let bytes = !streaming && info.st_mode & S_IFMT == S_IFREG ? info.st_size : 0 + guard bytes >= 0, bytes <= limits.resourceBytes - size.bytes, + name.utf8.count <= limits.resourceBytes - size.bytes - Int(bytes) else { throw CoreError.invalidState("transaction tree exceeds resource limits") } if let maximumFileBytes, - depth != 0 || info.st_mode & S_IFMT != S_IFREG || size > maximumFileBytes + depth != 0 || info.st_mode & S_IFMT != S_IFREG || bytes > maximumFileBytes { throw CoreError.invalidState("file exceeds the admitted byte limit") } - bytes += Int(size) + name.utf8.count + size.entries += 1 + size.bytes += Int(bytes) + name.utf8.count + size.depth = max(size.depth, depth) + try size.validate(limits: limits) } } private static func read( _ name: String, from parent: DirectoryHandle, relative: String, budget: inout CaptureBudget, + streaming: Bool = false, streamingIdentity: FileObjectIdentity? = nil, + streamingChildren: [String: FileObjectIdentity] = [:], admit: ((String, stat) throws -> Void)? = nil, collect: ((String, mode_t, Data, Bool) throws -> Void)? ) throws -> FileSnapshot? { guard let before = try parent.info(name) else { return nil } + let streaming = streaming || streamingIdentity == FileObjectIdentity(before) try admit?(relative, before) - try budget.consume(name, info: before, depth: relative.split(separator: "/").count) + try budget.consume( + name, info: before, + depth: relative.utf8.filter { $0 == 47 }.count + (relative.isEmpty ? 0 : 1), + streaming: streaming) let children: [Member]? let payload: Data + var streamedDigest: String? switch before.st_mode & S_IFMT { case S_IFDIR: let directory = try parent.child(name, matching: before) var entries: [Member] = [] let names = try budget.recursive - ? directory.names(maximumCount: budget.limits.entries - budget.entries) : [] + ? directory.names(maximumCount: budget.limits.entries - budget.size.entries) : [] for child in names { guard let value = try read( child, from: directory, relative: relative.isEmpty ? child : relative + "/" + child, - budget: &budget, admit: admit, collect: collect) + budget: &budget, streaming: streaming, streamingIdentity: streamingChildren[child], + admit: admit, collect: collect) else { throw CoreError.invalidState("entry changed while reading: \(child)") } @@ -235,9 +277,24 @@ struct FileSnapshot: Codable, Equatable, Sendable { }) case S_IFREG: children = nil - payload = try parent.read( - name, matching: before, - maximumBytes: budget.maximumFileBytes ?? budget.limits.resourceBytes) + if streaming { + guard let size = Int(exactly: before.st_size), size >= 0 else { + throw CoreError.invalidState("invalid transaction file size: " + name) + } + var hasher = SHA256() + let read = try parent.readChunks(name, matching: before, maximumBytes: size) { + hasher.update(bufferPointer: $0) + } + guard read == size else { + throw CoreError.invalidState("file size changed while reading: " + name) + } + streamedDigest = hasher.finalize().map { String(format: "%02x", $0) }.joined() + payload = Data() + } else { + payload = try parent.read( + name, matching: before, + maximumBytes: budget.maximumFileBytes ?? budget.limits.resourceBytes) + } case S_IFLNK: children = nil payload = try parent.readLinkData(name) @@ -248,7 +305,8 @@ struct FileSnapshot: Codable, Equatable, Sendable { } try collect?(relative, before.st_mode & S_IFMT, payload, before.st_mode & 0o111 != 0) return FileSnapshot( - identity: FileObjectIdentity(before), digest: FileHash.sha256Hex(data: payload), + identity: FileObjectIdentity(before), + digest: streamedDigest ?? FileHash.sha256Hex(data: payload), executable: before.st_mode & S_IFMT == S_IFREG && before.st_mode & 0o111 != 0, mode: before.st_mode & 0o7777, children: children) @@ -294,12 +352,17 @@ struct FileSnapshot: Codable, Equatable, Sendable { func containsRemaining(_ current: FileSnapshot) -> Bool { guard identity == current.identity else { return false } guard let children, let remaining = current.children else { return self == current } + guard permitsDisposalMode(current.mode) else { return false } let recorded = Dictionary( uniqueKeysWithValues: children.map { (Data($0.name.utf8), $0.snapshot) }) return remaining.allSatisfy { member in recorded[Data(member.name.utf8)]?.containsRemaining(member.snapshot) == true } } + + func permitsDisposalMode(_ observed: mode_t) -> Bool { + observed == mode || observed == mode | S_IRWXU + } } /// Required journal classification. Optional metadata is required by validation whenever diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift index e8208f1..19a8df9 100644 --- a/Sources/AgentsCore/TransactionJournal.swift +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -33,7 +33,7 @@ struct TransactionJournal: Codable { if finalized { let terminalProgress: Set = phase == .committed - ? [.applied] : [.queued, .ready, .restored, .cancelled] + ? [.applied, .skipped] : [.queued, .ready, .restored, .cancelled, .skipped] guard entries.allSatisfy({ terminalProgress.contains($0.progress) }) else { throw CoreError.invalidState("finalized transaction contradicts its terminal outcome") } @@ -81,11 +81,14 @@ struct TransactionJournal: Codable { case restored /// Original modes are restored; publication did not consume private staging. case cancelled + /// Deferred ledger evidence matched its preimage, so no replacement was constructed. + case skipped var permitsDirectoryWrite: Bool { self == .publishing || self == .restoring } } struct Conflict: Codable { + static let reasonBytes = 1024 let reason: String /// Scope-relative destinations and container locations, never executable input paths. let locations: [String] @@ -106,6 +109,14 @@ struct TransactionJournal: Codable { var coordination: Int? var coordinationRoot: String? var name: String { String(path.split(separator: "/").last!) } + + var streamingPreimage: FileObjectIdentity? { + guard TransactionPaths.isMaterializedPin(path), let preimage, preimage.identity.isDirectory, + security.preimage == .ordinary, security.preimageAccess == nil, + security.preimageTreeAccess == nil + else { return nil } + return preimage.identity + } } struct Container: Codable { @@ -201,7 +212,8 @@ struct TransactionLayout { case externalTo(FileObjectIdentity) func matches( - _ name: String, from parent: DirectoryHandle, permittingDirectoryWrite: Bool = false + _ name: String, from parent: DirectoryHandle, permittingDirectoryWrite: Bool = false, + streamingPreimage: FileObjectIdentity? = nil ) throws -> Bool { switch self { case .any: return true @@ -212,7 +224,10 @@ struct TransactionLayout { guard try parent.info(name).map(FileObjectIdentity.init) == expected.identity else { return false } - return try FileSnapshot.read(name, from: parent).map { + return try FileSnapshot.read( + name, from: parent, + streaming: expected.identity == streamingPreimage ? streamingPreimage : nil + ).map { expected.matches($0, permittingDirectoryWrite: permittingDirectoryWrite) } == true } @@ -222,7 +237,9 @@ struct TransactionLayout { let target: Target let objects: [TransactionSlot: FileSnapshot] - static func expected(_ entry: TransactionJournal.Entry) -> [Self] { + static func expected(_ entry: TransactionJournal.Entry, checkingSkippedPreimage: Bool = true) + -> [Self] + { let prepared: Self let installed: Self let reverted: Self @@ -249,6 +266,9 @@ struct TransactionLayout { switch entry.progress { case .queued: return [Self(kind: .construction, target: .any, objects: [:])] case .ready, .cancelled: return [prepared] + case .skipped: + let target: Target = checkingSkippedPreimage ? .object(entry.preimage!) : .any + return [Self(kind: .prepared, target: target, objects: [:])] case .publishing: // A deletion has no slot object before its rename, so only the target can tell a // prepared deletion from an installed one. diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 8eeb0fc..a97ab35 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -5,6 +5,31 @@ import Foundation struct TransactionPaths { let store: StateStore + static func isMaterializedPin(_ path: String) -> Bool { + let parts = path.split(separator: "/", omittingEmptySubsequences: false) + guard parts.count == 5, parts[0] == "state", parts[1] == "cache", parts[2] == "materialized", + SourceCache.isObjectID(String(parts[4])) + else { return false } + let key = parts[3].utf8 + guard (66...125).contains(key.count), key.dropLast(64).last == 45 else { return false } + let prefix = key.dropLast(65) + return prefix.first != 45 && prefix.first != 46 + && prefix.allSatisfy { + (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 46 || $0 == 95 + } + && key.suffix(64).allSatisfy { (97...102).contains($0) || (48...57).contains($0) } + } + + func pinParent(_ path: String) throws -> DirectoryHandle? { + let coordinates = try components(path) + guard Self.isMaterializedPin(path) else { + throw CoreError.unsafePath("invalid materialized pin destination") + } + var parent = try store.openDirectoryIfPresent() + for part in coordinates.descendants.dropLast() { parent = try parent?.directory(part) } + return parent + } + func path( for destination: URL, skillInitialization: SkillInitializationTarget? = nil, installation: SkillInstallationTarget? = nil diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift index 1aba19b..39986b6 100644 --- a/Sources/AgentsCore/TransactionPublication.swift +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -48,15 +48,18 @@ extension TransactionSession { let entry = journal.entries[index] let parent = parents[index] let container = try self.container(entry.container) - if let preimage = entry.preimage { try parent.synchronize(entry.name, as: preimage) } + if let preimage = entry.preimage { + try parent.synchronize(entry.name, as: preimage, streaming: entry.streamingPreimage) + } try emit(.stage(index, .preimageSynced)) let staging = TransactionSlot.staging(for: entry) var staged: FileSnapshot? + var workIdentity: FileObjectIdentity? if source != nil || entry.security.replacement == .privateMaterialization { let sealed = try construct( source, expectation: expectation, named: staging.name(index), index: index, container: container, parent: parent, privateData: privateData, privateTree: privateTree, - previousReceipt: previousReceipt) + previousReceipt: previousReceipt, workIdentity: &workIdentity) try emit(.stage(index, .constructed)) let capture = try FileSnapshot.capture(staging.name(index), from: container) try verify(source, sealed, capture: capture) @@ -64,6 +67,7 @@ extension TransactionSession { throw conflict(index, "missing constructed object") } staged = snapshot + stagedSizes[index] = capture.size if entry.security.replacement == .privateMaterialization { journal.entries[index].security.stagedAccess = try container.requirePrivateAccess( staging.name(index)) @@ -73,6 +77,9 @@ extension TransactionSession { } else { try emit(.stage(index, .constructed)) } + if let workIdentity { + try container.remove(TransactionSlot.work.name(index), identity: workIdentity) + } for slot in TransactionSlot.objectSlots where entry.action == .delete || slot != staging { guard try container.info(slot.name(index)) == nil else { throw CoreError.invalidState("unexpected private recovery slot before sealing") @@ -88,7 +95,7 @@ extension TransactionSession { _ source: FileTransaction.Source?, expectation: FileTransaction.Expectation, named name: String, index: Int, container: DirectoryHandle, parent: DirectoryHandle, privateData: (() throws -> PrivateMaterializationResult)?, privateTree: PrivateTree?, - previousReceipt: MaterializationReceipts.Record? + previousReceipt: MaterializationReceipts.Record?, workIdentity: inout FileObjectIdentity? ) throws -> FileTransaction.Expectation { let entry = journal.entries[index] var expectation = expectation @@ -155,7 +162,8 @@ extension TransactionSession { try copy(url, named: name, index: index, container: container) case .prepared(let produce): let work = TransactionSlot.work.name(index) - try container.makeDirectory(work, syncParent: false) + let directory = try container.makeDirectory(work, syncParent: false) + workIdentity = try directory.objectIdentity try emit(.stage(index, .workCreated)) let root = container.url.appendingPathComponent(work) let url = try produce(root) @@ -246,6 +254,7 @@ extension TransactionSession { } // A stale preparation cancels from ready; rechecking after the intent narrows the race. try requirePreimage(index) + if entry.progress == .skipped { return } try advance(index, to: .publishing) try requirePreimage(index) try emit(.publication(index, .validated)) @@ -281,8 +290,8 @@ extension TransactionSession { try entry.security.validateObject(preimage, named: entry.name, in: parents[index]) } guard - try FileSnapshot.read(journal.entries[index].name, from: parents[index]) - == journal.entries[index].preimage + try FileSnapshot.read(entry.name, from: parents[index], streaming: entry.streamingPreimage) + == entry.preimage else { throw conflict(index, "preparation is stale; prepare again") } diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift index 249717c..986fe77 100644 --- a/Sources/AgentsCore/TransactionRecovery.swift +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -104,7 +104,7 @@ extension FileTransaction { try session.emit(.journalSynced) if journal.phase == .applying { try session.rollback() } if session.journal.phase == .applying || session.journal.phase == .preparing { - try session.sealDisposal() + try session.sealDisposal(rollingBack: true) try session.finish(.rolledBack) if outcome?.journalID == journal.id { outcome?.recordTerminal(.rolledBack) } try session.emit(.phase(.rolledBack)) @@ -284,7 +284,8 @@ extension TransactionSession { if journal.disposing { try verifyTarget(index) } else { - _ = try distribution(index, permittingDirectoryWrite: true) + _ = try distribution( + index, permittingDirectoryWrite: true, rollingBack: journal.phase != .committed) try inspectDirectoryPermissions(index) } } @@ -313,13 +314,13 @@ extension TransactionSession { } private func rollbackEntry(_ index: Int) throws { - let layout = try distribution(index, permittingDirectoryWrite: true) + let layout = try distribution(index, permittingDirectoryWrite: true, rollingBack: true) let progress = journal.entries[index].progress if progress == .ready { try advance(index, to: .cancelled) return } - if progress == .cancelled || progress == .restored { return } + if progress == .cancelled || progress == .restored || progress == .skipped { return } if layout.kind == .prepared { try restoreDirectoryPermissions(index, purpose: .cancelRestore) _ = try distribution(index) diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift index 619bd3b..ddaead8 100644 --- a/Sources/AgentsCore/TransactionSession.swift +++ b/Sources/AgentsCore/TransactionSession.swift @@ -30,6 +30,9 @@ final class TransactionSession { var privateTreeBytes = 0 var privateNativeArrays: [Int: [PrivateNativeArrayRecord]] = [:] + private(set) var persistedByteCount = 0 + var preimageSizes: [Int: FileSnapshot.CaptureSize] = [:] + var stagedSizes: [Int: FileSnapshot.CaptureSize] = [:] func sealNativeArrays(_ arrays: [PrivateNativeArrayRecord]?, for index: Int) throws { var candidate = privateNativeArrays @@ -56,10 +59,16 @@ final class TransactionSession { with: bytes, afterWrite: { try emit(.persisted(journal.phase, change, .written)) + if case .terminal = change, journal.phase == .committed { + for index in journal.entries.indices where journal.entries[index].progress == .skipped { + try requirePreimage(index) + } + } }, afterRename: { try emit(.persisted(journal.phase, change, .renamed)) }) + persistedByteCount = bytes.count } /// Transitions and their durable evidence promises are changed together. The first @@ -67,9 +76,9 @@ final class TransactionSession { func advance(_ index: Int, to next: TransactionJournal.Progress) throws { let previous = journal.entries[index].progress let legal: [TransactionJournal.Progress: Set] = [ - .queued: [.ready], .ready: [.publishing, .cancelled], + .queued: [.ready, .skipped], .ready: [.publishing, .cancelled], .publishing: [.applied, .restoring, .cancelled], .applied: [.restoring], - .restoring: [.restored], .restored: [], .cancelled: [], + .restoring: [.restored], .restored: [], .cancelled: [], .skipped: [], ] guard legal[previous]?.contains(next) == true else { throw conflict(index, "illegal progress transition: \(previous) -> \(next)") @@ -137,7 +146,9 @@ final class TransactionSession { func recordConflict(_ index: Int, _ error: Error) throws { journal.entries[index].conflict = .init( - reason: String(describing: error), + reason: String( + decoding: String(describing: error).utf8.prefix( + TransactionJournal.Conflict.reasonBytes - 3), as: UTF8.self), locations: [journal.entries[index].path, containerLocation(index)]) try persist(.conflict(index, journal.entries[index].progress)) } @@ -145,12 +156,12 @@ final class TransactionSession { func container(_ index: Int) throws -> DirectoryHandle { let record = journal.containers[index] let parent = parents[record.entry] - guard let expected = record.identity, - try parent.info(record.name).map(FileObjectIdentity.init) == expected + guard let expected = record.identity, let observed = try parent.info(record.name), + FileObjectIdentity(observed) == expected, observed.st_mode & 0o7777 == 0o700 else { throw conflict(record.entry, "private container identity changed or is missing") } - let handle = try parent.child(record.name) + let handle = try parent.child(record.name, matching: observed) guard try handle.objectIdentity == expected else { throw conflict(record.entry, "private container changed while opening") } @@ -266,14 +277,20 @@ final class TransactionSession { let entry = journal.entries[index] let allowed: Set switch journal.phase { - case .preparing: allowed = [.queued, .ready] - case .applying: allowed = [.ready, .publishing, .applied, .restoring, .restored, .cancelled] - case .committed: allowed = [.applied] - case .rolledBack: allowed = [.queued, .ready, .restored, .cancelled] + case .preparing: allowed = [.queued, .ready, .skipped] + case .applying: + allowed = [.ready, .publishing, .applied, .restoring, .restored, .cancelled, .skipped] + case .committed: allowed = [.applied, .skipped] + case .rolledBack: allowed = [.queued, .ready, .restored, .cancelled, .skipped] } - let requiresStaging = entry.action == .install && entry.progress != .queued + let skipped = entry.progress == .skipped + let requiresStaging = entry.action == .install && entry.progress != .queued && !skipped guard allowed.contains(entry.progress), (entry.staged != nil) == requiresStaging, + !skipped + || (entry.path == "state/" + StateStore.resolvedFileName + && entry.action == .install && entry.preimage?.isRegular == true + && !entry.security.isPrivate), !journal.disposing || journal.phase == .committed || journal.phase == .rolledBack else { throw conflict(index, "operation progress contradicts its evidence or journal phase") @@ -282,12 +299,15 @@ final class TransactionSession { /// Matches the target and every recovery slot against the operation/progress table. /// Only interrupted publishing or restoring may observe a leased owner-write bit. - func distribution(_ index: Int, permittingDirectoryWrite: Bool = false) throws + func distribution( + _ index: Int, permittingDirectoryWrite: Bool = false, rollingBack: Bool = false + ) throws -> TransactionLayout { let entry = journal.entries[index] try requireParent(index) - let layouts = TransactionLayout.expected(entry) + let layouts = TransactionLayout.expected( + entry, checkingSkippedPreimage: !rollingBack && journal.phase != .rolledBack) if entry.progress == .queued { if entry.security.preimage == .privateMaterialization, let original = entry.preimage { try entry.security.validateObject(original, named: entry.name, in: parents[index]) @@ -298,7 +318,11 @@ final class TransactionSession { let permitsWrite = permittingDirectoryWrite && entry.progress.permitsDirectoryWrite var objects: [TransactionSlot: FileSnapshot] = [:] for slot in TransactionSlot.objectSlots { - if let value = try FileSnapshot.read(slot.name(index), from: container) { + let streaming = entry.streamingPreimage.flatMap { identity in + layouts.contains { $0.objects[slot]?.identity == identity } ? identity : nil + } + if let value = try FileSnapshot.read(slot.name(index), from: container, streaming: streaming) + { try entry.security.validateObject( value, named: slot.name(index), in: container, permittingDirectoryWrite: permitsWrite) objects[slot] = value @@ -322,7 +346,8 @@ final class TransactionSession { expected, named: entry.name, in: parents[index], permittingDirectoryWrite: permitsWrite) } if try layout.target.matches( - entry.name, from: parents[index], permittingDirectoryWrite: permitsWrite) + entry.name, from: parents[index], permittingDirectoryWrite: permitsWrite, + streamingPreimage: entry.streamingPreimage) { return layout } diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index ec0d6a6..4bcc98f 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -88,8 +88,10 @@ package struct StatePrecondition: PreparedEvidence { package struct TargetPrecondition: Sendable { package let url: URL let snapshot: FileSnapshot? + let size: FileSnapshot.CaptureSize private let identity: PathIdentity private let maximumFileBytes: Int? + private let pinStore: StateStore? private(set) var access: TargetAccessPrecondition? package var exists: Bool { snapshot != nil } @@ -102,16 +104,51 @@ package struct TargetPrecondition: Sendable { package init(_ url: URL) throws { self.url = url.standardizedFileURL maximumFileBytes = nil + pinStore = nil identity = try PathIdentity(url) - snapshot = try FileSnapshot.read(at: url) + (snapshot, size) = try FileSnapshot.measure(at: url) try identity.validate() } - private init(url: URL, snapshot: FileSnapshot?, identity: PathIdentity, maximumFileBytes: Int?) { + private init( + url: URL, snapshot: FileSnapshot?, size: FileSnapshot.CaptureSize, identity: PathIdentity, + maximumFileBytes: Int? + ) { self.url = url.standardizedFileURL self.snapshot = snapshot + self.size = size self.identity = identity self.maximumFileBytes = maximumFileBytes + self.pinStore = nil + } + + /// A pin precondition reads the old tree through the scope's checked cache ancestry. + package init(materializedPin url: URL, store: StateStore) throws { + let paths = TransactionPaths(store: store) + let path = try paths.path(for: url) + let parent = try paths.pinParent(path) + let receipts = try store.materializationReceipts(for: path) + let receipt = receipts.records.targets[try store.materializationReceiptKey(for: path)] + let observed = try parent?.info(url.lastPathComponent).map(FileObjectIdentity.init) + let streaming = receipt == nil && observed?.isDirectory == true ? observed : nil + self.url = url.standardizedFileURL + identity = try PathIdentity(url) + maximumFileBytes = nil + pinStore = store + if let parent { + (snapshot, size) = try FileSnapshot.measure( + url.lastPathComponent, from: parent, streaming: streaming) + } else { + (snapshot, size) = (nil, .init()) + } + guard snapshot?.identity == observed, snapshot?.identity.isDirectory != false else { + throw CoreError.invalidState("materialized pin is not a stable directory: \(url.path)") + } + try identity.validate() + } + + package func snapshotDigest() throws -> String? { + try snapshot.map(ResolvedLedgerCodec.digest) } /// Rendering and its expected preimage use the same opened-file bytes and inode. @@ -127,7 +164,8 @@ package struct TargetPrecondition: Sendable { return ( capture.bytes, Self( - url: url, snapshot: capture.snapshot, identity: identity, maximumFileBytes: maximumFileBytes + url: url, snapshot: capture.snapshot, size: capture.size, identity: identity, + maximumFileBytes: maximumFileBytes ) ) } @@ -152,10 +190,15 @@ package struct TargetPrecondition: Sendable { } func validateSnapshot() throws { - let current = - try maximumFileBytes.map { - try FileSnapshot.captureFile(at: url, maximumFileBytes: $0).snapshot - } ?? FileSnapshot.read(at: url) + let current: FileSnapshot? + if let pinStore { + current = try Self(materializedPin: url, store: pinStore).snapshot + } else { + current = + try maximumFileBytes.map { + try FileSnapshot.captureFile(at: url, maximumFileBytes: $0).snapshot + } ?? FileSnapshot.read(at: url) + } guard current == snapshot else { throw CoreError.invalidState("target changed during preparation: \(url.path)") } diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index fd0de04..225c11f 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -644,11 +644,10 @@ public struct WatchOperations: Sendable { private func units( _ source: SourceDeclaration, revision: String, cache: SourceCache ) throws -> [WatchItemKey: WatchUnit] { - let id = try source.identity(environment: cache.store.environment) - let locked = LockedSource( - kind: source.kind, url: source.kind == .git ? source.gitURL : nil, - requirement: source.requirement, path: source.path) - return try cache.withSnapshot(sourceID: id, source: locked, revision: revision) { snapshot in + try cache.withGitSelection( + source, revision: revision, + selections: [.init(path: source.path ?? ".", optional: true)], offline: false + ) { snapshot in let root = try PathSafety.resolvedChild(base: snapshot, subpath: source.path ?? ".") guard FileManager.default.fileExists(atPath: root.path) else { return [:] } var result: [WatchItemKey: WatchUnit] = [:] diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index 8ad1e29..a04c601 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -58,9 +58,12 @@ extension InstructionOperations { .missingLock, "Instruction declaration has no lock; update can reconstruct it.", store.resolvedURL) } - let sources = InstructionSources(store: store) let targets = InstructionTargets(store: store) - var unchanged = true + let policy = try SourcePolicySnapshot(store: store) + let inputs = try InstructionDoctor.auditInputs( + ledger, roots: roots, store: store, sourcePolicy: policy.effective) + diagnostics += inputs.diagnostics + var changedOwnPaths = Set() if scope == .project { let project = environment.projectDirectory.resolvingSymlinksInPath() let records = @@ -71,7 +74,7 @@ extension InstructionOperations { let file = project.appendingPathComponent(record.path) let current = try FileSystem.readUnlessDenied(at: file) if current.map(Instructions.hash) != record.hash { - unchanged = false + changedOwnPaths.insert(record.path) report( .ownChanged, "Own instructions file changed since the lock; run 'agents update': \(record.name)", @@ -122,13 +125,33 @@ extension InstructionOperations { } else if bytes == nil { report(.missingTarget, "Generated instructions file is missing.", file) } - if unchanged, let ids = owners[key], - let sections = try? sources.restoreLockedSections(ids, in: ledger, roots: roots), - !sections.isEmpty - { - let text = try Instructions.render(sections) - for problem in targets.linkProblems(in: text, file: file, key: key) { - report(.invalidLink, "Link '\(problem.destination)' \(problem.reason).", file) + if let ids = owners[key] { + let components = ids.compactMap { ledger.components[$0] } + let healthy = components.allSatisfy { component in + component.resources.allSatisfy { inputs.bytes[$0] != nil } + && !component.resources.contains { id in + guard let resource = ledger.resources[id], + let source = ledger.sources[resource.source] + else { return false } + return source.revision == "live" && source.location?.root == "project" + && changedOwnPaths.contains(resource.path) + } + } + if healthy { + var seen = Set() + let sections = try components.compactMap { component -> InstructionSection? in + guard let id = component.resources.first, seen.insert(id).inserted, + let bytes = inputs.bytes[id], let resource = ledger.resources[id] + else { return nil } + return try Instructions.validateSource( + bytes, id: resource.path, allowRestrictions: true) + } + if !sections.isEmpty { + let text = try Instructions.render(sections) + for problem in targets.linkProblems(in: text, file: file, key: key) { + report(.invalidLink, "Link '\(problem.destination)' \(problem.reason).", file) + } + } } } } catch { @@ -210,8 +233,8 @@ extension InstructionOperations { reportedUnreadable: unreadableTargets) } diagnostics += InstructionSourceDiagnostics.inspect( - store: store, declaration: declaration, lock: lock, - sourcePolicy: try SourcePolicySnapshot(store: store).effective, + store: store, declaration: declaration, ledger: ledger, roots: roots, + sourcePolicy: policy.effective, bundledSources: try ledger.bundledSourceIdentities(in: store, roots: roots)) return InstructionDoctorReport( root: root, @@ -247,6 +270,112 @@ extension InstructionOperations { } private enum InstructionDoctor { + static func auditInputs( + _ ledger: ResolvedLedger, roots: [String: URL], store: StateStore, + sourcePolicy: EffectiveSourcePolicy + ) throws -> (bytes: [String: Data], diagnostics: [InstructionDiagnostic]) { + let components = ledger.components.values.filter { $0.kind == "instructions" } + let ids = Set(components.flatMap(\.resources)) + let units = Dictionary(grouping: components.filter { !$0.resources.isEmpty }) { + $0.resources[0] + } + let pins = try LedgerGitPin.collect(ledger, roots: roots, ids: ids) + let pinByResource = Dictionary( + uniqueKeysWithValues: pins.values.flatMap { pin in + pin.resources.keys.map { ($0, pin) } + }) + let cache = SourceCache(store: store, sourcePolicy: sourcePolicy) + return try SourceResolutionSession.withTemporaryRead(store: store, sourcePolicy: sourcePolicy) { + session in + var inputs: [String: Data] = [:] + var diagnostics: [InstructionDiagnostic] = [] + var support: [RetentionReferences.Git: Result] = [:] + for id in ids.sorted() { + guard let resource = ledger.resources[id] else { continue } + let identity = try ledger.sourceIdentity(resource.source, roots: roots) + let source = try ledger.rootSource(resource.source) + var path: URL? + do { + let bytes: Data + if let pin = pinByResource[id] { + let destination = cache.materializedURL( + sourceID: pin.key.source, revision: pin.key.revision) + path = try PathSafety.resolvedChild(base: destination, subpath: resource.path) + guard + let tree = try cache.existingPinnedTree( + sourceID: pin.key.source, revision: pin.key.revision) + else { throw CoreError.notFound("materialized instruction input") } + var canonical: URL? + if resource.support.contains(where: { $0.kind == .file }) { + if support[pin.key] == nil { + support[pin.key] = Result { try session.lockedGitTree(pin, offline: true) } + } + canonical = try support[pin.key]!.get() + } + try pin.verify(resource, in: tree, authenticatingSupportFrom: canonical) + bytes = try FileSystem.read(at: pin.file(resource, in: tree)) + } else if let archive = source.archive, resource.kind == .archive, + let transport = source.transport + { + let tree = cache.archiveTree(transport: transport, evidence: archive) + let file = try PathSafety.resolvedChild(base: tree, subpath: resource.path) + path = file + try InstructionSnapshotReader.requireNoLinks( + file, + in: .init( + snapshot: .init(source: identity, revision: source.revision), + pin: nil, root: tree)) + bytes = try FileSystem.read(at: file) + } else { + guard + let object = resource.entries.first(where: { $0.path == "." && $0.kind == .file })? + .object, + let content = ledger.contentObjects[object] + else { throw CoreError.invalidState("missing locked instruction content") } + bytes = content + } + guard Instructions.hash(bytes) == resource.hash else { + throw CoreError.invalidState("locked instruction digest mismatch") + } + if let records = units[id] { + let section = try Instructions.validateSource( + bytes, id: resource.path, allowRestrictions: true) + guard + records.allSatisfy({ + ($0.payload.object?["sourceHash"]?.text ?? resource.hash) == section.hash + }) + else { throw CoreError.invalidState("locked instruction section digest mismatch") } + } + inputs[id] = bytes + } catch { + diagnostics.append( + .init( + kind: .stateUnavailable, + message: + "Cannot verify locked instruction input \(identity) at \(source.revision)/\(resource.path): \(error)", + path: path)) + } + } + let appends = try Set( + components.compactMap { + try $0.payload.object?["localAppend"].map(LedgerLocation.init(ledgerValue:)) + }) + for appendix in appends.sorted(by: { ($0.root ?? "", $0.path) < ($1.root ?? "", $1.path) }) { + let path = try appendix.resolve(roots: roots) + do { + _ = try appendix.readContainedFile(roots: roots) + } catch { + diagnostics.append( + .init( + kind: .stateUnavailable, + message: "Cannot read instruction appendix \(appendix.path): \(error)", + path: path)) + } + } + return (inputs, diagnostics) + } + } + static func ancestors(of root: URL) -> [URL] { var result: [URL] = [] var cursor = root.resolvingSymlinksInPath() diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 5665521..39bd3de 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -75,13 +75,15 @@ extension InstructionOperations { guard source.kind != .wellKnown else { throw CoreError.unsupported("instructions require source files") } + let view: SourceSnapshot if try session.isGitSource(source) { - let units = try InstructionSources(store: store, resolutions: session).discover( - source, cacheSource: false) - try policy.validate() - return units + guard + let pin = try session.candidates(for: source, requirements: [source.requirement]).first + else { throw CoreError.invalidSource("source has no matching revision") } + view = try session.snapshot(source, at: pin) + } else { + view = try session.localSnapshot(source) } - let view = try session.localSnapshot(source) let units = try InstructionSnapshotReader.read(view).map { unit in InstructionUnit( record: LockedSection( diff --git a/Sources/AgentsInstructions/InstructionSnapshotReader.swift b/Sources/AgentsInstructions/InstructionSnapshotReader.swift index dd92021..6012756 100644 --- a/Sources/AgentsInstructions/InstructionSnapshotReader.swift +++ b/Sources/AgentsInstructions/InstructionSnapshotReader.swift @@ -16,10 +16,11 @@ package enum InstructionSnapshotReader { guard Declaration.isInstructionName(name) else { throw CoreError.invalidSource("invalid instruction name: \(name)") } - let root = try view.directory() + let root = try view.directory(requiringContents: false) let container = root.lastPathComponent == ".agent" ? "instructions" : InstructionSources.ownContainer - let file = root.appendingPathComponent(container).appendingPathComponent(name + ".md") + let file = try view.discoveryResource( + container + "/" + name + ".md", recursive: false, followsLinks: false, optional: true) let path = try view.relativePath(file) try InstructionSources.requireNoLinks(file, below: view.root) guard FileManager.default.fileExists(atPath: file.path) else { return nil } @@ -29,7 +30,7 @@ package enum InstructionSnapshotReader { package static func read(_ view: SourceSnapshot, own: Bool = false) throws -> [SnapshotInstruction] { - let root = try view.directory() + let root = try view.directory(requiringContents: false) let containers = own ? [root.lastPathComponent == ".agent" ? "instructions" : InstructionSources.ownContainer] @@ -37,7 +38,8 @@ package enum InstructionSnapshotReader { var names = Set() var result: [SnapshotInstruction] = [] for container in containers { - let directory = root.appendingPathComponent(container) + let directory = try view.discoveryResource( + container, recursive: true, followsLinks: false, optional: true) for (name, file) in try InstructionSources.files(in: directory, tree: view.root) { try Task.checkCancellation() guard names.insert(name).inserted else { diff --git a/Sources/AgentsInstructions/InstructionSourceDiagnostics.swift b/Sources/AgentsInstructions/InstructionSourceDiagnostics.swift index 8c23f8d..5c4c22a 100644 --- a/Sources/AgentsInstructions/InstructionSourceDiagnostics.swift +++ b/Sources/AgentsInstructions/InstructionSourceDiagnostics.swift @@ -2,79 +2,151 @@ import AgentsCore import Foundation enum InstructionSourceDiagnostics { + struct RevisionKey: Hashable { + let identity: String + let sourceKind: SourceKind + let location: Data + let requirementKind: String? + let value: String? + let upperBound: String? + + init(identity: String, source: SourceDeclaration) { + let requirement = source.requirement?.canonical + self.identity = identity + sourceKind = source.kind + location = Data(source.location.utf8) + requirementKind = requirement?.kind + value = requirement?.value + upperBound = requirement?.upperBound + } + } + static func inspect( - store: StateStore, declaration: Declaration, lock: ResolvedState, + store: StateStore, declaration: Declaration, ledger: ResolvedLedger, roots: [String: URL], sourcePolicy: EffectiveSourcePolicy, bundledSources: Set - ) - -> [InstructionDiagnostic] - { - var diagnostics: [InstructionDiagnostic] = [] + ) -> [InstructionDiagnostic] { let cache = SourceCache(store: store, sourcePolicy: sourcePolicy) - let sections = lock.instructions.sections + lock.instructions.chatgpt.values.flatMap(\.sections) - for (id, source) in lock.sources.sorted(by: { $0.key < $1.key }) { - let pins = sections.filter { $0.source == id } - guard !pins.isEmpty, !bundledSources.contains(id) else { continue } - let root = - source.kind == .local ? URL(fileURLWithPath: String(id.dropFirst("local:".count))) : nil + var diagnostics: [InstructionDiagnostic] = [] + var revisions: [RevisionKey: Result] = [:] + var dirtyPaths: [URL: Set] = [:] + for (id, source) in ledger.sources.sorted(by: { $0.key < $1.key }) + where source.container == nil + && (SourceCache.isObjectID(source.revision) || source.archive != nil) + { + var identity = id + var root: URL? do { - let declared = try declaration.sources.values.first { - try $0.identity(environment: store.environment) == id + identity = try ledger.sourceIdentity(id, roots: roots) + guard !bundledSources.contains(identity) else { continue } + root = try source.location?.resolve(roots: roots) + func belongs(_ source: String) -> Bool { + var source = source + while let parent = ledger.sources[source]?.container { source = parent } + return source == id + } + let components = ledger.components.values.filter { component in + component.kind == "instructions" + && (belongs(component.source) + || component.resources.contains { + ledger.resources[$0].map { belongs($0.source) } ?? false + }) } - let current = try cache.inspectRevision( - declared ?? cache.declaration(sourceID: id, source: source)) - func differs(_ section: LockedSection) -> Bool { - section.source == id - && (section.revision != current.revision || section.version != current.version) + guard !components.isEmpty else { continue } + var uses = ledger.sourceUses.filter { $0.source == id } + if uses.isEmpty { + uses = Set(components.map(\.root)).sorted().map { .init(source: id, root: $0) } } - let outdated = pins.filter(differs) - if !outdated.isEmpty { - let previous = Set( - outdated.map { pin in - (pin.revision ?? "missing") + (pin.version.map { " (\($0))" } ?? "") + for use in uses { + let owned = components.filter { component in + if component.root == use.root { return true } + let path = component.resources.first.flatMap { ledger.resources[$0]?.path } + return path.map { + InstructionSnapshotReader.searchRoots(of: $0, name: component.name).contains(use.root) + } ?? false + } + guard !owned.isEmpty else { continue } + if let root { + dirtyPaths[root, default: []].formUnion( + owned.flatMap(\.resources).compactMap { resource in + guard let resource = ledger.resources[resource], belongs(resource.source) else { + return nil + } + return resource.path + }) + } + let candidates = try declaration.sources.sorted(by: { $0.key < $1.key }).map(\.value) + .filter { + try $0.identity(environment: store.environment) == identity + && PathSafety.sanitizeSubpath($0.path ?? ".") == use.root } - ).sorted().joined(separator: ", ") - let selected = current.revision + (current.version.map { " (\($0))" } ?? "") - let files = lock.instructions.sections.filter(differs).map(\.name).joined(separator: ", ") - let prompts = lock.instructions.chatgpt.filter { - $0.value.sections.contains(where: differs) + let declared = + candidates.first { + switch ($0.requirement, use.requirement) { + case (nil, nil): return true + case (let lhs?, let rhs?): return lhs.declarationEquivalent(to: rhs) + default: return false + } + } ?? (candidates.count == 1 ? candidates.first : nil) + let locked = LockedSource( + kind: source.kind, url: source.transport, requirement: use.requirement, + path: use.root == "." ? nil : use.root) + let selectedSource = try declared ?? cache.declaration(sourceID: identity, source: locked) + let key = RevisionKey(identity: identity, source: selectedSource) + let evidence = revisions[key] ?? Result { try cache.inspectRevision(selectedSource) } + revisions[key] = evidence + let current = try evidence.get() + let outdated = owned.filter { + source.revision != current.revision || $0.version != current.version + } + if !outdated.isEmpty { + let files = Set(outdated.filter { !$0.chatGPT }.map(\.name)).sorted() + let prompts = Set( + outdated.filter(\.chatGPT).compactMap { $0.payload.object?["prompt"]?.text } + ).sorted() + let before = source.revision + (source.version.map { " (\($0))" } ?? "") + let after = current.revision + (current.version.map { " (\($0))" } ?? "") + var message = + "Matching source revision differs from locked pins: \(identity) at \(use.root): \(before) -> \(after)." + if !files.isEmpty { message += " File sections: \(files.joined(separator: ", "))." } + if !prompts.isEmpty { + message += " ChatGPT prompt pins: \(prompts.joined(separator: ", "))." + } + diagnostics.append(.init(kind: .sourceUpdateAvailable, message: message, path: root)) } - .keys.sorted().joined(separator: ", ") - var message = - "Matching source revision differs from locked pins: \(id): \(previous) -> \(selected)." - if !files.isEmpty { message += " File sections: \(files)." } - if !prompts.isEmpty { message += " ChatGPT prompt pins: \(prompts)." } - diagnostics.append( - InstructionDiagnostic(kind: .sourceUpdateAvailable, message: message, path: root)) } } catch { diagnostics.append( - InstructionDiagnostic( + .init( kind: .sourceResolutionFailed, - message: "Cannot resolve instruction source \(id): \(error)", - path: root)) + message: "Cannot resolve instruction source \(identity): \(error)", path: root)) } - if let root { - do { - let paths = Set(pins.map(\.path)).sorted() - let output = try ProcessRunner.git( - [ - "--no-optional-locks", "-C", root.path, "status", "--porcelain", - "--untracked-files=all", "--", - ] + paths, operation: .readStatus, source: root.path - ).stdout - if !output.isEmpty { - diagnostics.append( - InstructionDiagnostic( - kind: .uncommittedSource, - message: "Local source has uncommitted selected instructions: \(id)", - path: root)) + } + for (root, paths) in dirtyPaths.sorted(by: { $0.key.path < $1.key.path }) where !paths.isEmpty { + do { + func git(_ args: [String]) throws -> String { + let result = try ProcessRunner.isolatedGit( + ["--no-optional-locks", "--literal-pathspecs"] + args, in: root) + guard result.exitCode == 0 else { + throw CoreError.invalidSource( + "Git could not read local worktree state: " + result.stderr) } - } catch { + return result.stdout.trimmingCharacters(in: .newlines) + } + guard try git(["rev-parse", "--is-inside-work-tree"]) == "true" else { continue } + let output = try git( + ["status", "--porcelain", "--untracked-files=all", "--"] + paths.sorted()) + if !output.isEmpty { diagnostics.append( - InstructionDiagnostic( - kind: .stateUnavailable, message: "Cannot inspect local instruction source: \(error)", - path: root)) + .init( + kind: .uncommittedSource, + message: "Local source has uncommitted selected instructions:\n" + output, path: root) + ) } + } catch { + diagnostics.append( + .init( + kind: .stateUnavailable, message: "Cannot inspect local instruction source: \(error)", + path: root)) } } return diagnostics diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index f3ec837..93d8356 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -9,57 +9,10 @@ final class InstructionSources { static let containers = ["instructions", ".agents/instructions"] let store: StateStore - let cache: SourceCache - let resolutions: SourceResolutionSession? - private var discovered: [String: [InstructionUnit]] = [:] - private var restored: [String: InstructionSection] = [:] private var ownUnits: [InstructionUnit]? - init(store: StateStore, resolutions: SourceResolutionSession? = nil) { - self.resolutions = resolutions + init(store: StateStore) { self.store = store - cache = SourceCache(store: store) - } - - func discover(_ source: SourceDeclaration, cacheSource: Bool = true) throws -> [InstructionUnit] { - let id = try source.identity(environment: store.environment) - if let units = discovered[id] { return units } - guard source.kind != .wellKnown else { - throw CoreError.unsupported("instructions require a Git source") - } - if source.kind == .local { - let directory = source.localURL(environment: store.environment) - let root = try ProcessRunner.git( - ["-C", directory.path, "rev-parse", "--show-toplevel"], - operation: .findRepositoryRoot, source: source.location - ).stdout.trimmingCharacters(in: .whitespacesAndNewlines) - guard - URL(fileURLWithPath: root).resolvingSymlinksInPath() == directory.resolvingSymlinksInPath() - else { throw CoreError.invalidSource("use the local Git root and a search path") } - } - func read(_ pin: SourceRevision, _ tree: URL) throws -> [InstructionUnit] { - let root = try PathSafety.resolvedChild(base: tree, subpath: source.path ?? ".") - var units: [InstructionUnit] = [] - for container in Self.containers { - let directory = root.appendingPathComponent(container) - for (name, file) in try Self.files(in: directory, tree: tree) { - let section = try Instructions.validateSource( - FileSystem.read(at: file), id: id + ":" + name) - units.append( - InstructionUnit( - record: LockedSection( - name: name, source: id, revision: pin.revision, version: pin.version, - path: PathSafety.relativePath(file.path, to: tree.path), hash: section.hash), - section: section)) - } - } - return try Self.unique(units) - } - let units = - try resolutions.map { try $0.withSnapshot(source, read) } - ?? cache.withResolvedSnapshot(source, cacheSource: cacheSource, read) - discovered[id] = units - return units } /// The project's own instructions, read from the working tree as it is. @@ -101,49 +54,6 @@ final class InstructionSources { section: section) } - /// Reads only the source entries owned by the target, using the ledger and existing cache. - func restoreLockedSections( - _ owners: [String], in ledger: ResolvedLedger, roots: [String: URL] - ) throws -> [InstructionSection] { - var seenResources = Set() - return try owners.compactMap { owner in - guard let component = ledger.components[owner], let id = component.resources.first, - let resource = ledger.resources[id] - else { throw CoreError.invalidState("missing locked instruction input") } - guard seenResources.insert(id).inserted else { return nil } - if let section = restored[id] { return section } - let bytes: Data - if resource.kind == .git { - var sourceID = resource.source - while let container = ledger.sources[sourceID]?.container { sourceID = container } - guard let source = ledger.sources[sourceID] else { - throw CoreError.invalidState("missing locked instruction source") - } - let sourceIdentity = try ledger.sourceIdentity(sourceID, roots: roots) - let materialized = cache.materializedURL( - sourceID: sourceIdentity, revision: source.revision) - try cache.validatePath(materialized) - let file = try PathSafety.resolvedChild(base: materialized, subpath: resource.path) - try Self.contained(file, in: materialized) - bytes = try FileSystem.read(at: file) - } else { - guard - let object = resource.entries.first(where: { $0.path == "." && $0.kind == .file })? - .object, - let content = ledger.contentObjects[object] - else { throw CoreError.invalidState("missing locked instruction content") } - bytes = content - } - let section = try Instructions.validateSource( - bytes, id: resource.path, allowRestrictions: true) - guard section.hash == resource.hash, - section.hash == (component.payload.object?["sourceHash"]?.text ?? resource.hash) - else { throw CoreError.invalidState("locked instruction digest mismatch: " + resource.path) } - restored[id] = section - return section - } - } - /// `alias:name` for a declared source, or nil for a bare name of the project's own instructions. static func split(_ reference: String) -> (alias: String, name: String)? { guard let colon = reference.firstIndex(of: ":") else { return nil } diff --git a/Sources/AgentsSkills/Discovery.swift b/Sources/AgentsSkills/Discovery.swift index 803bd1c..a622437 100644 --- a/Sources/AgentsSkills/Discovery.swift +++ b/Sources/AgentsSkills/Discovery.swift @@ -94,11 +94,12 @@ enum Discovery { } static func discover( - in base: URL, subpath: String? = nil, options: DiscoveryOptions = DiscoveryOptions() + in base: URL, subpath: String? = nil, options: DiscoveryOptions = DiscoveryOptions(), + snapshot: SourceSnapshot? = nil ) throws -> [Skill] { let searchRoot = try subpath.map { try PathSafety.resolvedChild(base: base, subpath: $0) } ?? base - let plugins = try pluginSkills(base: searchRoot) + let plugins = try pluginSkills(base: searchRoot, snapshot: snapshot) let projectInstalledSkillNames = projectInstalledAgentSkillNames(base: searchRoot) var skills: [Skill] = [] var seen = Set() @@ -301,7 +302,7 @@ enum Discovery { (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true } - private static func pluginSkills(base: URL) throws + private static func pluginSkills(base: URL, snapshot: SourceSnapshot?) throws -> (directories: [URL], groups: [String: String]) { var directories: [URL] = [] @@ -310,7 +311,20 @@ enum Discovery { let maximumManifestBytes = 16 * 1024 * 1024 func metadataBytes(_ path: String) throws -> Data? { - let file = base.appendingPathComponent(path).resolvingSymlinksInPath() + let candidate = base.appendingPathComponent(path) + let source: URL + if let snapshot { + // Discovery already expanded this subtree. Only an on-disk entry can supply metadata. + var info = stat() + if lstat(candidate.path, &info) != 0, errno == ENOENT || errno == ENOTDIR { + return nil + } + source = try snapshot.discoveryResource(path, recursive: false, optional: true) + guard FileManager.default.fileExists(atPath: source.path) else { return nil } + } else { + source = candidate + } + let file = source.resolvingSymlinksInPath() guard !isDirectory(file) else { return nil } let input = try TargetPrecondition.readingFile(file, maximumFileBytes: maximumManifestBytes) return input.bytes diff --git a/Sources/AgentsSkills/SkillSnapshotReader.swift b/Sources/AgentsSkills/SkillSnapshotReader.swift index 83d19d2..7cd8313 100644 --- a/Sources/AgentsSkills/SkillSnapshotReader.swift +++ b/Sources/AgentsSkills/SkillSnapshotReader.swift @@ -33,17 +33,20 @@ package enum SkillSnapshotReader { } base = root } else { + _ = try view.directory() base = view.root } let selected = try SourceSnapshot( snapshot: view.snapshot, pin: view.pin, root: base, discoveryPath: view.discoveryPath, localEnvironment: view.localEnvironment, liveRoot: view.liveRoot, - packageIdentity: view.packageIdentity) + packageIdentity: view.packageIdentity, expand: live ? nil : view.expand) var options = DiscoveryOptions(fullDepth: true) options.strict = true options.selecting = selecting - let skills = try Discovery.discover(in: base, subpath: selected.discoveryPath, options: options) + let skills = try Discovery.discover( + in: base, subpath: selected.discoveryPath, options: options, + snapshot: selected.expand == nil ? nil : selected) return try skills.filter { selecting?($0.name, URL(fileURLWithPath: $0.path).lastPathComponent) ?? true }.map { diff --git a/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift b/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift index ffcd8d3..34533e9 100644 --- a/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift +++ b/Sources/AgentsUpdates/HostPlugins/HostPluginTarget.swift @@ -88,10 +88,9 @@ struct HostPluginTarget: Sendable { try SourceResolutionSession.withTemporaryRead(store: stored.store) { session in let snapshot = try session.localSnapshot( .init(kind: .local, location: stored.source.path, path: source.path)) - let relative = try snapshot.relativePath( - snapshot.directory().appendingPathComponent(manifest)) + let file = try snapshot.discoveryResource(manifest, recursive: false, optional: true) return try TargetPrecondition.readingFile( - snapshot.resource(relative), maximumFileBytes: ManifestLimits.Input.bytes + file, maximumFileBytes: ManifestLimits.Input.bytes ).bytes } } diff --git a/Sources/AgentsUpdates/InstructionOperations.swift b/Sources/AgentsUpdates/InstructionOperations.swift index 2216e12..544a985 100644 --- a/Sources/AgentsUpdates/InstructionOperations.swift +++ b/Sources/AgentsUpdates/InstructionOperations.swift @@ -295,10 +295,10 @@ extension InstructionOperations { throw InstructionError.emptyPrompt } return try LedgerReplay.withLockedResources( - ledger, store: store, roots: store.ledgerRoots, limits: .standard + ledger, store: store, roots: store.ledgerRoots, limits: .standard, lowerings: [lowering.id] ) { _, resources, _ in let bytes = try LedgerReplay.exportPrompt( - lowering, ledger: ledger, resources: resources, roots: store.ledgerRoots) + lowering, ledger: ledger, resources: resources.files, roots: store.ledgerRoots) let paths = try UpdateOperations.readLocations( declarations: [declaration], ledgers: [ledger], store: store) try baseline.validate() diff --git a/Sources/AgentsUpdates/MaterializedPinPlan.swift b/Sources/AgentsUpdates/MaterializedPinPlan.swift new file mode 100644 index 0000000..89999c3 --- /dev/null +++ b/Sources/AgentsUpdates/MaterializedPinPlan.swift @@ -0,0 +1,212 @@ +import AgentsCore +import Components +import Foundation + +/// Each prepared change owns the only transaction operation for its materialized pin. +struct MaterializedPinPlan: PreparedEvidence { + enum Action: String, Encodable { case keep, create, replace, delete } + + struct Decision: Encodable { + let path: String + let action: Action + let preimage: String? + let closure: String? + let live: String? + } + + private struct Change { + let precondition: TargetPrecondition + let replacement: TargetPrecondition? + } + + private struct Kept { + let pin: LedgerGitPin + let root: URL + let digest: String + } + + let decisions: [Decision] + private let changes: [Change] + private let kept: [Kept] + let locations: [URL] + var hasChanges: Bool { !changes.isEmpty } + var createsPins: Bool { decisions.contains { $0.action == .create } } + + init( + request: UpdateRequest, previous: ResolvedLedger, next: ResolvedLedger, store: StateStore, + roots: [String: URL], snapshotRoots: [String: URL], workspace: URL + ) throws { + let cache = SourceCache(store: store) + let prior = try LedgerGitPin.collect(previous, roots: roots) + let candidate = try LedgerGitPin.collect(next, roots: roots) + let filtered = + request.kinds != nil || !request.names.isEmpty || request.selectedIdentities != nil + let restoring: Bool = if case .restore = request.operation { true } else { false } + let maintainsCache = !filtered && !restoring + let before = try RetentionReferences(ledger: previous, roots: roots) + let after = try RetentionReferences(ledger: next, roots: roots) + let directories = (before.live + after.live).sorted { $0.path < $1.path } + let aliases = (before.liveAliases + after.liveAliases).sorted { $0.path < $1.path } + let selected = try Self.selectedResources(request, in: next, roots: roots) + .union(Self.selectedResources(request, in: previous, roots: roots)) + let relevant = Set(candidate.keys).union(prior.keys).filter { key in + guard filtered else { return candidate[key] != nil || maintainsCache } + if let nextPin = candidate[key], + nextPin.resources.keys.contains(where: { + prior[key]?.resources[$0] == nil + }) + { + return true + } + return (prior[key]?.resources.keys.contains(where: selected.contains) ?? false) + || (candidate[key]?.resources.keys.contains(where: selected.contains) ?? false) + } + let sorted = relevant.sorted { ($0.source, $0.revision) < ($1.source, $1.revision) } + var decisions: [Decision] = [] + var changes: [Change] = [] + var kept: [Kept] = [] + var locations: [URL] = [] + func record(_ url: URL, logicalPath: String, pin: LedgerGitPin?, allowShrink: Bool) throws { + let physical = url.deletingLastPathComponent().resolvingSymlinksInPath() + .appendingPathComponent(url.lastPathComponent) + let veto = + directories.first { + PathSafety.isContained($0, in: physical) || PathSafety.isContained(physical, in: $0) + } ?? aliases.first { PathSafety.isContained($0, in: physical) } + let existing = FileManager.default.fileExists(atPath: url.path) + var replacement: TargetPrecondition? + var digest: String? + let action: Action + if let pin { + let closure = try pin.closureDigest(snapshotRoots: snapshotRoots) + digest = closure + var satisfied = existing + if existing { + for (id, resource) in pin.resources.sorted(by: { $0.key < $1.key }) { + let authority = snapshotRoots[id] + do { try pin.verify(resource, in: url, authenticatingSupportFrom: authority) } catch let + error as CoreError + { + switch error { + case .invalidState, .notFound: satisfied = false + default: throw error + } + } + } + } + if satisfied, try veto != nil || !allowShrink || pin.matchesRetainedPaths(url) { + action = .keep + kept.append(.init(pin: pin, root: url, digest: closure)) + } else { + if let veto { + throw CoreError.unsafePath( + "materialized pin \(logicalPath) overlaps live edit source \(veto.path)") + } + let assembly = workspace.appendingPathComponent( + "pin-" + UUID().uuidString, isDirectory: true) + try pin.assemble(from: snapshotRoots, at: assembly) + replacement = try TargetPrecondition(assembly) + action = existing ? .replace : .create + } + } else if existing, veto == nil { + action = .delete + } else { + action = .keep + } + var preimage: String? + if action != .keep { + let precondition = try TargetPrecondition(materializedPin: url, store: store) + guard precondition.exists == existing else { + throw CoreError.invalidState("materialized pin changed during planning: " + logicalPath) + } + preimage = try precondition.snapshotDigest() + changes.append(.init(precondition: precondition, replacement: replacement)) + } + locations.append(url) + decisions.append( + .init( + path: logicalPath, action: action, preimage: preimage, closure: digest, live: veto?.path)) + } + func logical(_ url: URL) -> String { + "cache/materialized/" + url.deletingLastPathComponent().lastPathComponent + "/" + + url.lastPathComponent + } + var seen = Set() + for key in sorted { + let url = + try cache.existingPinnedTree(sourceID: key.source, revision: key.revision) + ?? cache.materializedURL(sourceID: key.source, revision: key.revision) + let path = logical(url) + seen.insert(path) + try record(url, logicalPath: path, pin: candidate[key], allowShrink: maintainsCache) + } + if maintainsCache { + for url in try cache.existingMaterializedPins() where !seen.contains(logical(url)) { + try record(url, logicalPath: logical(url), pin: nil, allowShrink: false) + } + } + self.decisions = decisions + self.changes = changes + self.kept = kept + self.locations = locations + } + + private static func selectedResources( + _ request: UpdateRequest, in ledger: ResolvedLedger, roots: [String: URL] + ) throws -> Set { + let direct = try Set( + ledger.components.compactMap { id, component -> String? in + if let identities = request.selectedIdentities { + return try identities.contains( + LedgerImpact.identity(component, ledger: ledger, roots: roots)) + ? id : nil + } + let name = + component.kind == "skills" ? PathSafety.sanitizeName(component.name) : component.name + let kind = DeclaredComponentKind(rawValue: component.kind)! + return (request.kinds?.contains(kind) ?? true) + && (request.names.isEmpty || request.names.contains(name)) ? id : nil + }) + let parents = Set( + ledger.occurrences.filter { + direct.contains($0.component) && ledger.components[$0.component]?.kind == "plugin" + }.map(\.id)) + let members = ledger.occurrences.filter { + $0.pluginMember.map { parents.contains($0.parent) } ?? false + }.map(\.component) + return Set(direct.union(members).flatMap { ledger.components[$0]?.resources ?? [] }) + } + + func validate(excludingTargets targets: Set = []) throws { + for change in changes { + if !targets.contains(change.precondition.url.path) { try change.precondition.validate() } + try change.replacement?.validate() + } + for observation in kept { + var actual: [String: URL] = [:] + for (id, resource) in observation.pin.resources { + // The prepared closure digest below checks every support file against + // the authoritative bytes already authenticated at planning time. + try observation.pin.verify( + resource, in: observation.root, authenticatingSupportFrom: nil, uncoveredSupport: []) + actual[id] = observation.root + } + guard try observation.pin.closureDigest(snapshotRoots: actual) == observation.digest else { + throw CoreError.invalidState( + "materialized pin changed during preparation: " + observation.root.path) + } + } + } + + func stage(in transaction: FileTransaction) throws { + for change in changes { + if let replacement = change.replacement { + try transaction.replace( + change.precondition.url, with: .copy(replacement.url), + expecting: change.precondition) + } else { + try transaction.delete(change.precondition.url, expecting: change.precondition) + } + } + } +} diff --git a/Sources/AgentsUpdates/ProducerPatchPlan.swift b/Sources/AgentsUpdates/ProducerPatchPlan.swift index 3fcc92b..bb182cc 100644 --- a/Sources/AgentsUpdates/ProducerPatchPlan.swift +++ b/Sources/AgentsUpdates/ProducerPatchPlan.swift @@ -1,4 +1,5 @@ import AgentsCore +import Components import Foundation struct ProducerPatchNativeInputs: Equatable, Sendable { @@ -99,15 +100,15 @@ struct ProducerPatchPlan { } mutating func compare( - _ copy: ProducerPatchRoutes.Copy, resources: [String: URL], lineage: ProducerPatchLineage + _ copy: ProducerPatchRoutes.Copy, resources: ReplayedResources, lineage: ProducerPatchLineage ) throws { - let origin = try lineage.origin(for: copy, replayed: resources) + let origin = try lineage.origin(for: copy, replayed: resources.files) guard case .owned(let context) = origin else { if case .skip(let reason) = origin { try skip(copy.target, reason) } return } let record = lineage.resource(copy.resource) - guard let source = resources[copy.resource] else { + guard let source = resources.files[copy.resource] else { throw ProducerPatchError.lockedInputUnavailable } var pending: [Edit] = [] @@ -115,9 +116,8 @@ struct ProducerPatchPlan { record.entries, source: source, target: copy.target, prefix: record.path, context: context, pending: &pending) if let support = copy.support { - var root = source - for _ in record.path.split(separator: "/") where record.path != "." { - root.deleteLastPathComponent() + guard let root = resources.snapshotRoots[copy.resource] else { + throw ProducerPatchError.lockedInputUnavailable } try scan( record.support, source: root, target: support, prefix: ".", diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 7f6dc59..2b99c04 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -47,6 +47,9 @@ final class UpdatePlan { private let watch: WatchState private let declarationChange: DeclarationChange? private let aggregation: ArtifactAggregation + private let pins: MaterializedPinPlan + private let ledgerReplacement: Data? + private let stagesDeferredLedger: Bool private let checkpoint: (String) throws -> Void private let provider: any RuntimeBindingProvider private let inputs: UpdateInputs @@ -253,10 +256,10 @@ final class UpdatePlan { offline: request.restoresOffline, sourcePolicy: sourcePolicy.effective, requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin, - acquisitions: acquisitions + acquisitions: acquisitions, previous: request.deployPendingMarketplace ? previous : nil ) { artifacts, resources, workspace in let publications = try MarketplaceGraphChange.restoreProducers( - next.marketplaceGraph, replayed: resources, store: store) + next.marketplaceGraph, replayed: resources.files, store: store) let removals = try request.deployPendingMarketplace ? MarketplaceGraphChange.pruneProducers( @@ -439,11 +442,13 @@ final class UpdatePlan { let native = try MarketplaceChanges.pin( lowered, declaration: candidate, previous: previous, request: request, store: store, sourceIDs: frozen.sources, producers: bundleSources.producers) + let migration = try AntigravityLedgerMigration(previous: previous, next: native) + let projectedPrevious = migration.projecting(previous, as: native) if marketplaceLock != nil { let identities = try MarketplaceGraphChange.deploymentIdentities( from: previous, to: native, roots: roots) try LedgerImpact.requireProtected( - previous: previous, next: native, kinds: Set(DeclaredComponentKind.allCases), + previous: projectedPrevious, next: native, kinds: Set(DeclaredComponentKind.allCases), roots: roots, selectedIdentities: identities) } @@ -456,10 +461,12 @@ final class UpdatePlan { let routes = try DeploymentConstruction.routes(native).union( DeploymentConstruction.routes(previous)) guard routes.isSubset(of: admitted) else { throw RequiredRoutes(routes: routes) } - if request.kinds != nil || !request.names.isEmpty || request.selectedIdentities != nil { + let filtered = + request.kinds != nil || !request.names.isEmpty || request.selectedIdentities != nil + if filtered { let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) try LedgerImpact.requireProtected( - previous: previous, next: native, kinds: kinds, names: Set(request.names), + previous: projectedPrevious, next: native, kinds: kinds, names: Set(request.names), roots: roots, selectedIdentities: request.selectedIdentities, retargetedInstructions: retargetedInstructions) } @@ -495,38 +502,61 @@ final class UpdatePlan { desired, store: store, roots: roots, limits: .standard, sourcePolicy: sourcePolicy.effective, requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin, - acquisitions: session.acquisitions - ) { next, artifacts, resources, workspace in - try MarketplaceGraphChange.validateProducers(next.marketplaceGraph, replayed: resources) + acquisitions: session.acquisitions, previous: previous, borrowed: session + ) { sealed, artifacts, resources, workspace in + try migration.prove(previous: previous, sealed: sealed, inputs: resources) + var next = sealed + try next.retainReachableContentObjects() + try MarketplaceGraphChange.validateProducers( + next.marketplaceGraph, replayed: resources.files) if let marketplaceLock, let graphChange = request.marketplaceGraphChange { return try marketplaceLock( MarketplaceLockPlan( store: store, baseline: baseline, sourcePolicy: sourcePolicy, organization: organization, initialFindings: initialFindings, graphChange: graphChange, previous: previous, desired: next, declaration: change, - roots: roots, resources: resources, + roots: roots, resources: resources.files, decisionInputs: complete.inputs, originalInputs: originals + importInputs + bundleSources.preconditions, acquisitions: session.acquisitions)) } - let removals = try MarketplaceGraphChange.pruneProducers( - previous: previous, next: next, store: store, roots: roots, - declaration: candidate, watch: watch) - return try body( - UpdatePlan( - request: request, store: store, roots: roots, baseline: baseline, - sourcePolicy: sourcePolicy, organization: organization, - initialFindings: initialFindings, - previous: previous, - next: next, - watch: watch, change: change, artifacts: artifacts, resources: resources, - workspace: workspace, - decisionInputs: complete.inputs, - originalInputs: originals + importInputs + bundleSources.preconditions, - checkpoint: checkpoint, provider: provider, installations: Array(installations.values), - retargetedInstructions: retargetedInstructions, - bundlePublications: bundleSources.publications, bundleRemovals: removals, - acquisitions: session.acquisitions)) + func prepare( + _ next: ResolvedLedger, _ artifacts: [ReplayedArtifact], _ resources: ReplayedResources, + _ workspace: URL, preserveLedger: Bool = false + ) throws -> T { + let removals = try MarketplaceGraphChange.pruneProducers( + previous: previous, next: next, store: store, roots: roots, + declaration: candidate, watch: watch) + return try body( + UpdatePlan( + request: request, store: store, roots: roots, baseline: baseline, + sourcePolicy: sourcePolicy, organization: organization, + initialFindings: initialFindings, + previous: previous, + next: next, + watch: watch, change: change, artifacts: artifacts, resources: resources, + workspace: workspace, + decisionInputs: complete.inputs, + originalInputs: originals + importInputs + bundleSources.preconditions, + checkpoint: checkpoint, provider: provider, + installations: Array(installations.values), + retargetedInstructions: retargetedInstructions, + bundlePublications: bundleSources.publications, bundleRemovals: removals, + acquisitions: session.acquisitions, preserveLedger: preserveLedger)) + } + if filtered, change == nil, + migration.onlyRepresentationChanged(previous: previous, sealed: next) + { + return try LedgerReplay.withLockedResources( + previous, store: store, roots: roots, limits: .standard, + sourcePolicy: sourcePolicy.effective, + requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin, + acquisitions: session.acquisitions + ) { artifacts, resources, workspace in + try prepare(previous, artifacts, resources, workspace, preserveLedger: true) + } + } + return try prepare(next, artifacts, resources, workspace) } } } @@ -578,13 +608,15 @@ final class UpdatePlan { sourcePolicy: SourcePolicySnapshot, organization: OrganizationInstallEvaluation, initialFindings: [OrganizationPolicyFinding], previous: ResolvedLedger, next: ResolvedLedger, watch: WatchState, - change: DeclarationChange?, artifacts: [ReplayedArtifact], resources: [String: URL], + change: DeclarationChange?, artifacts: [ReplayedArtifact], + resources replayed: ReplayedResources, workspace: URL, decisionInputs: [TargetPrecondition], originalInputs: [TargetPrecondition], checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, installations: [SkillInstallationTarget], retargetedInstructions: Set, bundlePublications: [BundleSourceInputs.Publication] = [], - bundleRemovals: [TargetPrecondition] = [], acquisitions: GitAcquisitionCaptures + bundleRemovals: [TargetPrecondition] = [], acquisitions: GitAcquisitionCaptures, + preserveLedger: Bool = false ) throws { self.store = store self.baseline = baseline @@ -601,13 +633,14 @@ final class UpdatePlan { deployPendingMarketplace = request.deployPendingMarketplace restoresOffline = request.restoresOffline self.acquisitions = acquisitions + let resources = replayed.files self.resources = resources inputs = try UpdateInputs( ledger: next, roots: roots, resources: resources, decisions: decisionInputs, originals: originalInputs + bundlePublications.map(\.destination) + bundleRemovals) aggregation = try ArtifactAggregation( ledger: next, previous: previous, artifacts: artifacts, - resources: resources, workspace: workspace, store: store, roots: roots, + resources: replayed, workspace: workspace, store: store, roots: roots, replace: request.replace, changingAccess: request.changingAccess, kinds: request.kinds, names: Set(request.names), selectedIdentities: request.selectedIdentities, @@ -635,7 +668,7 @@ final class UpdatePlan { } } } - self.next = aggregation.ledger + self.next = preserveLedger ? previous : aggregation.ledger try self.next.validate() workspacePolicy = try OrganizationWorkspaceInspection( evaluator: organization.evaluator, store: store, ledger: self.next, previous: previous, @@ -643,7 +676,21 @@ final class UpdatePlan { let policyReport = try organization.policy.report( initialFindings + organization.closure(self.next, roots: roots) + workspacePolicy.findings) try policyReport.requireAdmission() - let lockMissing = try baseline.bytes(for: store.resolvedURL) == nil + let lockBytes = try baseline.bytes(for: store.resolvedURL) + let lockMissing = lockBytes == nil + let stagesLedger = + try baseline.bytes(for: store.declarationURL) != nil || change != nil + || !lockMissing || previous.deployments != self.next.deployments + stagesDeferredLedger = stagesLedger && aggregation.hasDeferredLedgerEvidence + if stagesLedger { + ledgerReplacement = try ResolvedLedgerCodec.replacement( + self.next, existing: lockBytes, limits: .standard) + } else { + ledgerReplacement = nil + } + pins = try MaterializedPinPlan( + request: request, previous: previous, next: self.next, store: store, roots: roots, + snapshotRoots: replayed.snapshotRoots, workspace: workspace) let before = try previous.domainProjection(roots: roots) let after = try self.next.domainProjection(roots: roots) let allResults = try UpdateReporting.skills( @@ -701,6 +748,7 @@ final class UpdatePlan { let declaration: String? let marketplaceState: String? let targets: [String] + let pins: [MaterializedPinPlan.Decision] let instructionOutputs: [String: String] let sourcePolicy: String? let organizationPolicy: String? @@ -724,6 +772,7 @@ final class UpdatePlan { ? try MarketplaceGraphChange.stateDigest(in: baseline, store: store) : nil, targets: (aggregation.fingerprints + (try decisionInputs.map { try $0.displayEvidence(includeContent: false) })).sorted(), + pins: pins.decisions, instructionOutputs: Dictionary( uniqueKeysWithValues: instructions.outputs.map { ($0.id, FileHash.sha256Hex(data: $0.content)) @@ -746,7 +795,7 @@ final class UpdatePlan { let readPaths = try UpdateOperations.readLocations( declarations: readDeclarations, ledgers: [previous, self.next], store: store, roots: roots) - + decisionInputs.map(\.url) + installations.map(\.url) + + decisionInputs.map(\.url) + installations.map(\.url) + pins.locations + aggregation.instructionDecisionLocations + sourcePolicy.readDependencies.map(\.url) + organization.policy.readDependencies.map(\.url) + (marketplaceGraphChange?.directoryInputs.flatMap(\.readLocations) ?? []) @@ -754,7 +803,7 @@ final class UpdatePlan { report = CombinedUpdateReport( scope: store.scope, skills: publicResults, instructions: instructions, lockMissing: lockMissing, - hasChanges: self.next != previous || change != nil + hasChanges: ledgerReplacement != nil || pins.hasChanges || change != nil || !bundlePublications.isEmpty || !bundleRemovals.isEmpty || aggregation.needsRetainedArtifactPublication || aggregation.changes.contains(where: \.changed), @@ -825,6 +874,7 @@ final class UpdatePlan { try aggregation.validate() try aggregation.requireOwnership() try inputs.validate() + if !report.hasChanges { try pins.validate() } if report.hasChanges { let ledgerReferences = try RetentionReferences(ledger: next, roots: roots) var references = ledgerReferences @@ -838,7 +888,10 @@ final class UpdatePlan { previous: priorReferences, next: ledgerReferences, offline: restoresOffline ) { // A watch subscription is independent from install policy and already owns its own pins. - if !deployPendingMarketplace { + if !deployPendingMarketplace, + ledgerReplacement != nil || pins.createsPins + || aggregation.changes.contains(where: \.changed) + { try cache.retain( references: sourcePolicy.effective.isConfigured ? ledgerReferences : references, offline: restoresOffline) @@ -850,7 +903,9 @@ final class UpdatePlan { try marketplaceGraphChange?.validateCatalogs(in: store) let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) transaction.requireUnchanged( - since: baseline, aggregation, inputs, sourcePolicy, organization.policy, workspacePolicy) + since: baseline, aggregation, inputs, pins, sourcePolicy, organization.policy, + workspacePolicy) + try pins.stage(in: transaction) for publication in bundlePublications { try publication.stage(in: transaction) } for removal in bundleRemovals { try transaction.delete(removal.url, expecting: removal) } try aggregation.stage( @@ -858,13 +913,17 @@ final class UpdatePlan { roots: store.ledgerRoots(recordedIn: previous) ) try store.stageDeclaration(declarationChange, in: transaction, prepared: baseline) - // Empty scopes need no lock file; a declaration edit always accompanies first deployment. - if try store.declarationBytes(prepared: baseline) != nil || declarationChange != nil - || previous.deployments != next.deployments - { - try store.stageLedger( - producing: { self.aggregation.ledger }, limits: .standard, transaction: transaction, - prepared: baseline) + if stagesDeferredLedger { + let original = try baseline.bytes(for: store.resolvedURL) + try transaction.stageResolvedLedger(expecting: baseline.evidence(for: store.resolvedURL)) + { + try ResolvedLedgerCodec.replacement( + self.aggregation.ledger, existing: original, limits: .standard) + } + } else if let ledgerReplacement { + try transaction.replace( + store.resolvedURL, with: .data(ledgerReplacement), + expecting: baseline.evidence(for: store.resolvedURL)) } try cache.prune(references: references, transaction: transaction) try transaction.commit() diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift index 27688e8..42dd8ab 100644 --- a/Sources/AgentsUpdates/UpdateReporting.swift +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -119,7 +119,10 @@ enum UpdateReporting { let physicalMembers = Dictionary(grouping: membership) { InstructionLocations.physical(URL(fileURLWithPath: $0.path)).path } - for target in physicalMembers.keys.sorted() { + let physical = changes.contains { + $0.deployment.route == "agents/skill@1" && physicalMembers[$0.url.path] != nil && $0.changed + } + for target in physicalMembers.keys.sorted() where old != new || physical { let members = physicalMembers[target]! let retained = members.contains { $0.after != .absent } let oldFiles = try entries(URL(fileURLWithPath: target)) @@ -144,10 +147,6 @@ enum UpdateReporting { before: oldFiles[path], after: newFiles[path])) } } - let paths = Set(physicalMembers.keys) - let physical = changes.contains { - $0.deployment.route == "agents/skill@1" && paths.contains($0.url.path) && $0.changed - } return UpdateResult( skill: name, sourceIdentity: new?.source ?? old?.source ?? "", changed: old != new || physical, diff --git a/Sources/CPlatform/CPlatform.c b/Sources/CPlatform/CPlatform.c index 09be82c..1379e67 100644 --- a/Sources/CPlatform/CPlatform.c +++ b/Sources/CPlatform/CPlatform.c @@ -243,7 +243,7 @@ static int copy_xattrs(int source, int destination, const char *sourceLink, } #endif -int platform_copy_metadata(int source, int destination, mode_t mode) { +int platform_copy_metadata(int source, int destination, mode_t mode, bool durable) { #if defined(__APPLE__) if (fcopyfile(source, destination, NULL, COPYFILE_METADATA) < 0) return -1; #else @@ -256,11 +256,11 @@ int platform_copy_metadata(int source, int destination, mode_t mode) { if (futimens(destination, times) < 0) return -1; #endif if (fchmod(destination, mode & 07777) < 0) return -1; - return platform_sync(destination); + return durable ? platform_sync(destination) : 0; } int platform_copy_link_metadata(int sourceDirectory, const char *source, - int destinationDirectory, const char *destination) { + int destinationDirectory, const char *destination, bool durable) { #if defined(__APPLE__) int origin = openat(sourceDirectory, source, O_RDONLY | O_SYMLINK | O_CLOEXEC); if (origin < 0) return -1; @@ -268,7 +268,7 @@ int platform_copy_link_metadata(int sourceDirectory, const char *source, int result = -1; struct stat info; if (target >= 0 && fstat(origin, &info) == 0) { - result = platform_copy_metadata(origin, target, info.st_mode); + result = platform_copy_metadata(origin, target, info.st_mode, durable); } int error = errno; close(origin); @@ -276,6 +276,7 @@ int platform_copy_link_metadata(int sourceDirectory, const char *source, errno = error; return result; #else + (void)durable; // /proc/self/fd keeps both parent paths anchored to the pinned descriptors; // l*xattr and AT_SYMLINK_NOFOLLOW operate on the links, never their targets. char origin[64 + NAME_MAX], target[64 + NAME_MAX]; @@ -472,7 +473,7 @@ failed:; int platform_spawn(pid_t *pid, const char *executable, char *const argv[], char *const environment[], const char *directory, int lock, - bool inheritInput, int output, int error) { + int input, int output, int error) { posix_spawn_file_actions_t actions; posix_spawnattr_t attributes; int result = posix_spawn_file_actions_init(&actions); @@ -482,11 +483,13 @@ int platform_spawn(pid_t *pid, const char *executable, char *const argv[], #define CHECK(call) do { result = (call); if (result != 0) goto done; } while (0) #if defined(__APPLE__) CHECK(posix_spawnattr_setflags(&attributes, POSIX_SPAWN_CLOEXEC_DEFAULT)); - if (inheritInput) CHECK(posix_spawn_file_actions_addinherit_np(&actions, STDIN_FILENO)); + if (input == STDIN_FILENO) CHECK(posix_spawn_file_actions_addinherit_np(&actions, STDIN_FILENO)); #else - if (inheritInput) CHECK(posix_spawn_file_actions_adddup2(&actions, STDIN_FILENO, STDIN_FILENO)); + if (input == STDIN_FILENO) CHECK(posix_spawn_file_actions_adddup2(&actions, STDIN_FILENO, STDIN_FILENO)); #endif - if (!inheritInput) { + if (input > STDIN_FILENO) { + CHECK(posix_spawn_file_actions_adddup2(&actions, input, STDIN_FILENO)); + } else if (input < 0) { CHECK(posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0)); } // The _np spelling is required on macOS 15 and glibc 2.34. diff --git a/Sources/CPlatform/include/CPlatform.h b/Sources/CPlatform/include/CPlatform.h index 3f05e21..8c20b8a 100644 --- a/Sources/CPlatform/include/CPlatform.h +++ b/Sources/CPlatform/include/CPlatform.h @@ -38,9 +38,9 @@ bool platform_same_generation(const struct stat *first, const struct stat *secon int platform_sync(int descriptor); int platform_directory_birthtime(int descriptor, int64_t *seconds, int64_t *nanoseconds); int platform_copy_data(int source, int destination); -int platform_copy_metadata(int source, int destination, mode_t mode); +int platform_copy_metadata(int source, int destination, mode_t mode, bool durable); int platform_copy_link_metadata(int sourceDirectory, const char *source, - int destinationDirectory, const char *destination); + int destinationDirectory, const char *destination, bool durable); // ACL bytes are descriptor-derived, ordered, and platform-specific: Darwin's // external ACL representation or Linux's POSIX ACL xattr format. No names or @@ -68,6 +68,6 @@ void platform_dispose_file_access(struct platform_file_access *value); // In the child only stdin, stdout, stderr and the specified lock survive exec. int platform_spawn(pid_t *pid, const char *executable, char *const argv[], char *const environment[], const char *directory, int lock, - bool inheritInput, int output, int error); + int input, int output, int error); #endif diff --git a/Sources/Components/AntigravityLedgerMigration.swift b/Sources/Components/AntigravityLedgerMigration.swift new file mode 100644 index 0000000..9242382 --- /dev/null +++ b/Sources/Components/AntigravityLedgerMigration.swift @@ -0,0 +1,189 @@ +import AgentsCore +import AgentsInstructions +import Foundation + +/// Legacy representations are paired before selection checks and accepted only after rendering. +package struct AntigravityLedgerMigration { + private let oldToNew: [String: String] + private let oldResourcesToNew: [String: String] + + package init(previous: ResolvedLedger, next: ResolvedLedger) throws { + var components: [String: String] = [:] + var resources: [String: String] = [:] + let candidates = Dictionary(grouping: next.components.keys) { next.components[$0]!.source } + for (id, component) in previous.components + where component.kind == "instructions" && component.recipients.contains(.antigravity) { + for nextID in candidates[component.source, default: []].sorted() { + guard id != nextID, let nextComponent = next.components[nextID], + component.resources.count == nextComponent.resources.count + else { continue } + var comparable = nextComponent + comparable.resources = component.resources + guard comparable == component else { continue } + var converted: [String: String] = [:] + for (old, new) in zip(component.resources, nextComponent.resources) where old != new { + guard var before = previous.resources[old], let after = next.resources[new], + before.kind == .embedded, after.kind == .git, + try SourceCache.isObjectID(previous.rootSource(before.source).revision) + else { + converted.removeAll() + break + } + before.kind = .git + for i in before.entries.indices { before.entries[i].object = nil } + for i in before.support.indices { before.support[i].object = nil } + guard before == after else { + converted.removeAll() + break + } + converted[old] = new + } + guard !converted.isEmpty else { continue } + guard components[id] == nil, + converted.allSatisfy({ resources[$0.key] == nil || resources[$0.key] == $0.value }) + else { + throw CoreError.invalidState("requiresCombinedUpdate: ambiguous Antigravity inputs") + } + components[id] = nextID + resources.merge(converted) { prior, _ in prior } + } + } + oldToNew = components + oldResourcesToNew = resources + } + + package func projecting(_ previous: ResolvedLedger, as next: ResolvedLedger) -> ResolvedLedger { + var result = previous + for (old, new) in oldResourcesToNew { result.resources[old] = next.resources[new] } + return result + } + + package func prove( + previous: ResolvedLedger, sealed: ResolvedLedger, inputs: ReplayedResources + ) throws { + guard !oldToNew.isEmpty else { return } + func conflict(_ path: String) -> CoreError { + .invalidState("requiresCombinedUpdate: locked Antigravity contribution differs at " + path) + } + for (old, new) in oldResourcesToNew { + let before = previous.resources[old]! + guard let file = inputs.files[new], let root = inputs.snapshotRoots[new] else { + throw conflict(before.path) + } + let captured = try LedgerResources.capture( + file, embed: true, limits: .standard, sourceRoot: root) + guard captured.entries == before.entries, captured.support == before.support, + captured.hash == before.hash, + captured.objects.allSatisfy({ previous.contentObjects[$0.key] == $0.value }) + else { throw conflict(before.path) } + } + + let formats: Set = [ + AntigravityRuleV1.format, "agents/instructions@1", "agents/claude-import@1", + "agents/chatgpt@1", LockedLowering.instructionCopyFormat, + ] + let newIDs = Set(oldToNew.values) + let old = previous.lowerings.filter { + formats.contains($0.format) && $0.inputs.contains { oldToNew[$0] != nil } + } + let new = sealed.lowerings.filter { + formats.contains($0.format) && $0.inputs.contains(where: newIDs.contains) + } + guard Set(old.map(\.id)) == Set(new.map(\.id)) else { throw conflict("instruction outputs") } + for rule in old { + guard let result = new.first(where: { $0.id == rule.id }), result.format == rule.format, + equivalentLayout(rule, result), result.deployments == rule.deployments, + rule.inputs.compactMap({ oldToNew[$0] }) == result.inputs.filter(newIDs.contains) + else { throw conflict(rule.id) } + let sameInputs = rule.inputs.map { oldToNew[$0] ?? $0 } == result.inputs + if rule.format == AntigravityRuleV1.format || sameInputs { + guard rule.artifacts == result.artifacts, + rule.resources.map({ oldResourcesToNew[$0] ?? $0 }) == result.resources + else { throw conflict(rule.id) } + for id in rule.deployments { + guard var deployment = previous.deployments.first(where: { $0.id == id }) else { + throw conflict(rule.id) + } + deployment.owners = deployment.owners.map { oldToNew[$0] ?? $0 } + guard deployment == sealed.deployments.first(where: { $0.id == id }) else { + throw conflict(rule.id) + } + } + } else { + let relevant = Set( + rule.inputs.flatMap { id in + oldToNew[id] == nil ? [] : (previous.components[id]?.resources ?? []) + }) + let expected = rule.resources.filter(relevant.contains).map { oldResourcesToNew[$0] ?? $0 } + let owned = Set(expected) + guard expected == result.resources.filter(owned.contains) else { throw conflict(rule.id) } + } + } + } + + private func equivalentLayout(_ before: LockedLowering, _ after: LockedLowering) -> Bool { + if before.format != LockedLowering.instructionCopyFormat { + return before.layout == after.layout + } + guard var old = before.layout.object, var new = after.layout.object, + old.removeValue(forKey: "sectionCount")?.integer == before.inputs.count, + new.removeValue(forKey: "sectionCount")?.integer == after.inputs.count + else { return false } + return old == new + } + + package func onlyRepresentationChanged(previous: ResolvedLedger, sealed: ResolvedLedger) -> Bool { + guard !oldToNew.isEmpty else { return false } + var comparison = sealed + let owners = Dictionary(uniqueKeysWithValues: oldToNew.map { ($0.value, $0.key) }) + let inputs = Dictionary( + oldResourcesToNew.map { ($0.value, $0.key) }, + uniquingKeysWith: { prior, _ in prior }) + for (old, new) in oldToNew { + comparison.components[new] = nil + comparison.components[old] = previous.components[old] + } + for (old, new) in oldResourcesToNew { + if !comparison.components.values.contains(where: { $0.resources.contains(new) }) { + comparison.resources[new] = nil + } + let resource = previous.resources[old]! + comparison.resources[old] = resource + for object in (resource.entries + resource.support).compactMap(\.object) { + comparison.contentObjects[object] = previous.contentObjects[object] + } + } + for index in comparison.occurrences.indices { + let id = comparison.occurrences[index].component + comparison.occurrences[index].component = owners[id] ?? id + } + for index in comparison.lowerings.indices { + comparison.lowerings[index].inputs = comparison.lowerings[index].inputs.map { + owners[$0] ?? $0 + } + comparison.lowerings[index].resources = comparison.lowerings[index].resources.map { + inputs[$0] ?? $0 + } + } + for index in comparison.deployments.indices { + comparison.deployments[index].owners = comparison.deployments[index].owners.map { + owners[$0] ?? $0 + } + } + comparison.nativeAuthorities = previous.nativeAuthorities + // Private array deployments are recorded by aggregation after lowerings are sealed. + let privateDeployments = Set( + (previous.nativeAuthorities ?? []).flatMap(\.regions).flatMap { region in + region.path.contains { + if case .position(_, .privateArray) = $0 { return true } + return false + } ? region.deployments : [] + }) + var baseline = previous + baseline.deployments.removeAll { privateDeployments.contains($0.id) } + for index in baseline.lowerings.indices { + baseline.lowerings[index].deployments.removeAll(where: privateDeployments.contains) + } + return comparison == baseline + } +} diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift index e9bef7d..3baf75b 100644 --- a/Sources/Components/ArtifactAggregation.swift +++ b/Sources/Components/ArtifactAggregation.swift @@ -32,9 +32,11 @@ package final class ArtifactAggregation: PreparedEvidence { package private(set) var antigravityConflicts: [String] = [] package private(set) var instructionDecisionLocations: [URL] = [] package private(set) var needsRetainedArtifactPublication = false + package var hasDeferredLedgerEvidence: Bool { !nativePrivateWrites.isEmpty } private let store: StateStore private let roots: [String: URL] private let resources: [String: URL] + private let snapshotRoots: [String: URL] private let replace: Bool private let selectedKinds: Set? private let selectedNames: Set @@ -64,7 +66,7 @@ package final class ArtifactAggregation: PreparedEvidence { package init( ledger: ResolvedLedger, previous: ResolvedLedger, artifacts: [ReplayedArtifact], - resources: [String: URL], workspace: URL, store: StateStore, roots: [String: URL], + resources replayed: ReplayedResources, workspace: URL, store: StateStore, roots: [String: URL], replace: Bool, changingAccess: Bool, kinds: Set? = nil, names: Set = [], @@ -76,7 +78,9 @@ package final class ArtifactAggregation: PreparedEvidence { self.ledger = ledger self.store = store self.roots = roots + let resources = replayed.files self.resources = resources + snapshotRoots = replayed.snapshotRoots self.replace = replace if ledger.sources.values.contains(where: { $0.archive != nil }) { try SourceCache(store: store).requireArchivePublicationAccess() @@ -87,6 +91,11 @@ package final class ArtifactAggregation: PreparedEvidence { self.selectedIdentities = selectedIdentities self.retargetedInstructions = retargetedInstructions for (id, file) in resources where ledger.resources[id]?.kind != .liveEdit { + if let resource = ledger.resources[id], resource.kind == .git, + try file.standardizedFileURL == resourceDestination(id).standardizedFileURL + { + continue + } resourceEvidence.append(try TargetPrecondition(file)) } func selected(_ deployment: LedgerDeployment, in ledger: ResolvedLedger) throws -> Bool { @@ -102,7 +111,8 @@ package final class ArtifactAggregation: PreparedEvidence { retainedArtifactEvidence[destination.path] = input resourceEvidence.append(input) } - } else if resource.kind != .archive, FileManager.default.fileExists(atPath: destination.path) + } else if resource.kind != .archive, resource.kind != .git, + FileManager.default.fileExists(atPath: destination.path) { resourceEvidence.append(try TargetPrecondition(destination)) } @@ -114,9 +124,8 @@ package final class ArtifactAggregation: PreparedEvidence { try FileManager.default.copyItem( at: source, to: capsule.appendingPathComponent("payload")) } else { - var sourceRoot = source - if resource.path != "." { - for _ in resource.path.split(separator: "/") { sourceRoot.deleteLastPathComponent() } + guard let sourceRoot = snapshotRoots[id] else { + throw CoreError.invalidState("missing retained resource snapshot root") } let captured = try LedgerResources.capture( source, embed: true, limits: .standard, sourceRoot: sourceRoot) @@ -367,7 +376,15 @@ package final class ArtifactAggregation: PreparedEvidence { if deployment.route == "agents/skill@1" { if let prior = old.first, previous.components[prior.owners[0]]?.payload.object?["mode"]?.text != "edit", - let resolved = PathSafety.realPath(url.path), resolved != url.path + let resolved = PathSafety.realPath(url.path), resolved != url.path, + try !prior.owners.contains(where: { owner in + try (previous.components[owner]?.resources ?? []).contains { id in + guard previous.resources[id]?.kind == .git else { return false } + let destination = try resourceDestination(id, in: previous) + return PathSafety.realPath(destination.path)?.utf8.elementsEqual(resolved.utf8) + == true + } + }) { resourceEvidence.append(try TargetPrecondition(URL(fileURLWithPath: resolved))) } @@ -575,11 +592,11 @@ package final class ArtifactAggregation: PreparedEvidence { guard let evidence = source.archive, let transport = source.transport else { throw SourceAccessError.invalidArchive } - return SourceCache(store: store).archiveTree(transport: transport, evidence: evidence) - .appendingPathComponent(resource.path) + let root = SourceCache(store: store).archiveTree(transport: transport, evidence: evidence) + return resource.path == "." ? root : root.appendingPathComponent(resource.path) } if let root = try gitDestination(resource, ledger: ledger, store: store, roots: roots) { - return root.appendingPathComponent(resource.path) + return resource.path == "." ? root : root.appendingPathComponent(resource.path) } let base = store.cacheDirectory.appendingPathComponent( "artifact-content/" + String(id.dropFirst(7))) @@ -1812,12 +1829,8 @@ package final class ArtifactAggregation: PreparedEvidence { guard let source = resources[placement.resource], let resource = ledger.resources[placement.resource] else { throw CoreError.invalidState("missing generated native resource") } - var sourceRoot = source - if resource.path != "." { - for _ in resource.path.split(separator: "/") { sourceRoot.deleteLastPathComponent() } - } let captured = try LedgerResources.capture( - source, embed: true, limits: .standard, sourceRoot: sourceRoot) + source, embed: true, limits: .standard, sourceRoot: snapshotRoots[placement.resource]) guard captured.hash == resource.hash else { throw CoreError.invalidState("generated native resource changed") } @@ -2117,17 +2130,14 @@ package final class ArtifactAggregation: PreparedEvidence { var staged = Set() for (id, source) in resources.sorted(by: { $0.key < $1.key }) { guard let resource = ledger.resources[id], resource.kind != .liveEdit, - resource.kind != .archive + resource.kind != .archive, resource.kind != .git else { continue } let destination = try Self.resourceDestination(id, ledger: ledger, store: store, roots: roots) - let git = try Self.gitDestination(resource, ledger: ledger, store: store, roots: roots) let retainedArtifact = resource.kind == .artifact && resource.location != nil let container = - git - ?? (retainedArtifact - ? destination - : store.cacheDirectory.appendingPathComponent( - "artifact-content/" + String(id.dropFirst(7)))) + retainedArtifact + ? destination + : store.cacheDirectory.appendingPathComponent("artifact-content/" + String(id.dropFirst(7))) guard staged.insert(container.path).inserted else { continue } let artifactFlags = retainedArtifact @@ -2140,12 +2150,6 @@ package final class ArtifactAggregation: PreparedEvidence { guard actual.hash == resource.hash, artifactFlags.map({ $0 == actual.flags }) ?? true else { throw CoreError.invalidState("retained resource mismatch") } - } else if git != nil { - var root = source - if resource.path != "." { - for _ in resource.path.split(separator: "/") { root.deleteLastPathComponent() } - } - try transaction.replace(container, with: .copy(root)) } else if retainedArtifact { try transaction.replace( container, with: .copy(source), expectedHash: resource.hash, diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift index 6610d33..ee63d69 100644 --- a/Sources/Components/ComponentLinker.swift +++ b/Sources/Components/ComponentLinker.swift @@ -25,6 +25,9 @@ package enum ComponentLinker { requireRecordedTransport: organization.requiresRecordedGitOrigin, stagedLocalSources: stagedLocalSources, acquisitions: acquisitions ) { session in + if let ledger { + try session.preservingRetainedGit(in: ledger, roots: store.ledgerRoots(recordedIn: ledger)) + } let linker = Linking( document: document, store: store, platform: platform, session: session, directPins: directPins, retainedLedger: ledger, @@ -316,8 +319,10 @@ final class Linking { throw LinkError.invalid("producer-local source must stay inside its package", chain) } let relative = try PathSafety.sanitizeSubpath(raw) - let directory = try context.view.directory().appendingPathComponent(relative) - .standardizedFileURL + let directory = try context.view.directory(requiringContents: false).appendingPathComponent( + relative + ) + .standardizedFileURL let path = try context.view.relativePath(directory) let sourceID = path == "." @@ -327,7 +332,7 @@ final class Linking { let view = try SourceSnapshot( snapshot: SourceSnapshotID(source: sourceID, revision: context.view.snapshot.revision), pin: context.view.pin, root: context.view.root, discoveryPath: discoveryPath, - packageIdentity: context.view.packageIdentity) + packageIdentity: context.view.packageIdentity, expand: context.view.expand) guard source.requirement == nil else { throw LinkError.invalid("contained sources inherit their producer snapshot", chain) } @@ -436,7 +441,7 @@ final class Linking { func producer(_ view: SourceSnapshot, chain: [SourceSpan]) throws -> LinkingDocument { let key = GroupIdentity(snapshot: view.snapshot, root: view.discoveryPath, name: "") if let existing = documents[key] { return existing } - let root = try view.directory() + let root = try view.directory(requiringContents: false) let file = root.appendingPathComponent( root.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml") let relative = try view.relativePath(file) diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift index d7d5890..992deb2 100644 --- a/Sources/Components/Expansion.swift +++ b/Sources/Components/Expansion.swift @@ -709,7 +709,7 @@ final class Expansion { unit.bytes, path: unit.path, leaf: leaf, scope: linking.store.scope ) { path in try linking.budget.step() - let file = try view.resource(path) + let file = try view.resource(path, recursive: false, followsLinks: false) try InstructionSnapshotReader.requireNoLinks(file, in: view) guard let bytes = try TargetPrecondition.readingFile(file).bytes else { throw AntigravityRuleV1.failure(leaf, "included file does not exist: \(path)") @@ -779,10 +779,10 @@ final class Expansion { func resource(_ resourcePath: String, in view: SourceSnapshot, chain: [SourceSpan]) throws -> LinkedResource { - let root = try view.directory() + let root = try view.directory(requiringContents: false) let file = try PathSafety.resolvedChild(base: root, subpath: resourcePath) let path = try view.relativePath(file) - let target = try view.resource(path) + let target = try view.resource(path, recursive: true) var directory: ObjCBool = false guard FileManager.default.fileExists(atPath: target.path, isDirectory: &directory) else { throw LinkError.missing("resource '\(resourcePath)'", chain) diff --git a/Sources/Components/Import/ImportInput.swift b/Sources/Components/Import/ImportInput.swift index fa8df7f..8fd5202 100644 --- a/Sources/Components/Import/ImportInput.swift +++ b/Sources/Components/Import/ImportInput.swift @@ -35,9 +35,9 @@ enum ImportInput { guard limits.documentBytes >= 0, limits.documentBytes <= Int.max - 2, limits.depth > 0, limits.depth < Int.max, limits.nodes > 0, limits.nodes < Int.max else { throw ImportReadFailure.invalid } - return try TargetPrecondition.readingFile( - view.resource(document), maximumFileBytes: limits.documentBytes - ).bytes + let file = try view.resource(document, recursive: false, optional: true) + if view.expand != nil, !FileManager.default.fileExists(atPath: file.path) { return nil } + return try TargetPrecondition.readingFile(file, maximumFileBytes: limits.documentBytes).bytes } static func snapshot(_ root: URL) throws -> SourceSnapshot { diff --git a/Sources/Components/LedgerFreeze.swift b/Sources/Components/LedgerFreeze.swift index 9cee2ec..c690b2b 100644 --- a/Sources/Components/LedgerFreeze.swift +++ b/Sources/Components/LedgerFreeze.swift @@ -85,19 +85,13 @@ package enum LedgerFreeze { guard let base = locations.sources[resource.snapshot.source] else { throw CoreError.invalidState("live skill needs explicit location") } - var location = base - location.path = base.path == "." ? resource.path : base.path + "/" + resource.path record = .init( kind: .liveEdit, source: id, path: resource.path, hash: resource.hash, - entries: [], location: location) + entries: [], location: base.appendingAuthoredPath(resource.path)) } else { let url = try session.resource(snapshot: resource.snapshot, path: resource.path) let source = try ledger.rootSource(id) - // Rule replay needs only the matched bytes from the pinned snapshot. Embedding - // them avoids staging the producer's checkout as part of a small rule installation. - let git = - SourceCache.isObjectID(source.revision) - && !(component.key.kind == .instructions && component.recipients.contains(.antigravity)) + let git = SourceCache.isObjectID(source.revision) let kind: LedgerResource.Kind = source.archive != nil ? .archive : resource.artifact != nil ? .artifact : git ? .git : .embedded diff --git a/Sources/Components/LedgerImpact.swift b/Sources/Components/LedgerImpact.swift index c16dce7..e2267df 100644 --- a/Sources/Components/LedgerImpact.swift +++ b/Sources/Components/LedgerImpact.swift @@ -30,14 +30,24 @@ package struct LedgerImpact { let payload: LedgerValue let conditions: [LedgerCondition] let recipients: [AgentID] - let resources: [String] + let resources: [[String]] } let components = try ledger.components.values.map { c in Component( identity: try identity(c, ledger: ledger, roots: roots), revision: c.revision, mcpRegistry: c.mcpRegistry, payload: c.payload, conditions: c.conditions, recipients: c.recipients, - resources: c.resources.map { ledger.resources[$0]!.hash }) + resources: try c.resources.map { id in + let resource = ledger.resources[id]! + var evidence = [resource.path, resource.hash] + if resource.kind == .liveEdit, let location = resource.location { + evidence.append(try location.authoredPath(roots: roots)) + if let source = ledger.sources[resource.source]?.location { + evidence.append(try source.authoredPath(roots: roots)) + } + } + return evidence + }) }.sorted { if $0.identity != $1.identity { return $0.identity < $1.identity } return try ResolvedLedgerCodec.digest($0) < ResolvedLedgerCodec.digest($1) @@ -178,6 +188,7 @@ package struct LedgerImpact { || (!names.isEmpty && !names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)))) else { continue } + let live = c.resources.contains { ledger.resources[$0]?.kind == .liveEdit } func sourceChain(_ id: String) throws -> [LedgerSource] { var result: [LedgerSource] = [] var next: String? = id @@ -194,7 +205,9 @@ package struct LedgerImpact { } if let location = source.location { source.location = .init( - kind: .absolute, path: try location.resolve(roots: roots).path) + kind: .absolute, + path: try live + ? location.authoredPath(roots: roots) : location.resolve(roots: roots).path) } result.append(source) } @@ -203,10 +216,16 @@ package struct LedgerImpact { let sources = try [sourceChain(c.source), sourceChain(c.declaringSource)] + c.resources.map { try sourceChain(ledger.resources[$0]!.source) } - let resources = c.resources.enumerated().map { index, id in + let resources = try c.resources.enumerated().map { index, id in var resource = ledger.resources[id]! resource.source = "resource:" + String(index) - if resource.kind == .liveEdit { resource.hash = "live" } + if resource.kind == .liveEdit { + resource.hash = "live" + if let location = resource.location { + resource.location = .init( + kind: .absolute, path: try location.authoredPath(roots: roots)) + } + } return resource } if var payload = c.payload.object { diff --git a/Sources/Components/LedgerReplay.swift b/Sources/Components/LedgerReplay.swift index 54d8dad..6fe4794 100644 --- a/Sources/Components/LedgerReplay.swift +++ b/Sources/Components/LedgerReplay.swift @@ -63,6 +63,12 @@ package typealias LedgerRenderer = ( _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] ) throws -> [ReplayedArtifact] +/// A snapshot root is present when the borrowed file retains its locked source coordinates. +package struct ReplayedResources { + package let files: [String: URL] + package let snapshotRoots: [String: URL] +} + package enum LedgerReplay { /// Only formats with implemented production semantics are registered here. Tests explicitly /// supply their own renderer table; a format is never selected by agent or current version. @@ -99,12 +105,14 @@ package enum LedgerReplay { _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, offline: Bool = false, sourcePolicy: EffectiveSourcePolicy = .init(), requireRecordedTransport: Bool = false, acquisitions: GitAcquisitionCaptures? = nil, - _ body: (ResolvedLedger, [ReplayedArtifact], [String: URL], URL) throws -> T + previous: ResolvedLedger? = nil, borrowed: SourceResolutionSession? = nil, + _ body: (ResolvedLedger, [ReplayedArtifact], ReplayedResources, URL) throws -> T ) throws -> T { try run( ledger, store: store, roots: roots, limits: limits, renderers: nil, recording: true, offline: offline, sourcePolicy: sourcePolicy, - requireRecordedTransport: requireRecordedTransport, acquisitions: acquisitions + requireRecordedTransport: requireRecordedTransport, acquisitions: acquisitions, + previous: previous, borrowed: borrowed ) { artifacts, lowerings, resources, workspace in var candidate = ledger @@ -120,13 +128,15 @@ package enum LedgerReplay { sourcePolicy: EffectiveSourcePolicy = .init(), requireRecordedTransport: Bool = false, acquisitions: GitAcquisitionCaptures? = nil, additionalResources: Set = [], anchorLockedGit: Bool = false, - _ body: ([ReplayedArtifact], [String: URL], URL) throws -> T + previous: ResolvedLedger? = nil, + _ body: ([ReplayedArtifact], ReplayedResources, URL) throws -> T ) throws -> T { try run( ledger, store: store, roots: roots, limits: limits, renderers: nil, recording: false, selectedLowerings: selected, offline: offline, sourcePolicy: sourcePolicy, requireRecordedTransport: requireRecordedTransport, acquisitions: acquisitions, - additionalResources: additionalResources, anchorLockedGit: anchorLockedGit + additionalResources: additionalResources, anchorLockedGit: anchorLockedGit, + previous: previous ) { artifacts, _, resources, workspace in try body(artifacts, resources, workspace) } @@ -241,9 +251,10 @@ package enum LedgerReplay { sourcePolicy: EffectiveSourcePolicy = .init(), requireRecordedTransport: Bool = false, acquisitions: GitAcquisitionCaptures? = nil, selectedResources: Set? = nil, additionalResources: Set = [], anchorLockedGit: Bool = false, - completeSourceAdmission: Bool = true, + completeSourceAdmission: Bool = true, previous: ResolvedLedger? = nil, + borrowed: SourceResolutionSession? = nil, observeResource: ((String, URL, URL?) throws -> Void)? = nil, - _ body: ([ReplayedArtifact], [LockedLowering], [String: URL], URL) throws -> T + _ body: ([ReplayedArtifact], [LockedLowering], ReplayedResources, URL) throws -> T ) throws -> T { try ResolvedLedgerCodec.checkModel(ledger, limits: limits) try ledger.validate() @@ -288,7 +299,7 @@ package enum LedgerReplay { remaining -= size } } - for id in additionalResources.subtracting(lowerings.flatMap(\.resources)) { + for id in resourceIDs.subtracting(lowerings.flatMap(\.resources)) { let size = sizes[id]! guard size <= remaining else { throw CoreError.invalidState("replay input byte budget") } remaining -= size @@ -300,13 +311,81 @@ package enum LedgerReplay { acquisitions: acquisitions ) { session in var acquired: [String: URL] = [:] + var snapshotRoots: [String: URL] = [:] + let cache = SourceCache( + store: store, sourcePolicy: sourcePolicy, + requireRecordedTransport: requireRecordedTransport, + acquisitions: session.acquisitions) + let pins = try LedgerGitPin.collect(ledger, roots: roots, ids: resourceIDs) + let priorPins = try previous.map { try LedgerGitPin.collect($0, roots: roots) } ?? [:] + var trees: [String: (LedgerGitPin, URL)] = [:] + for pin in pins.values.sorted(by: { + ($0.key.source, $0.key.revision) < ($1.key.source, $1.key.revision) + }) { + try cache.requireGit(pin.source) + let existing = try cache.existingPinnedTree( + sourceID: pin.key.source, revision: pin.key.revision) + let prior = priorPins[pin.key] + let grows = + prior.map { prior in + pin.resources.keys.contains { prior.resources[$0] == nil } + } ?? false + if let prior { + if let existing { + try session.verifyRetainedGitTree(prior, in: existing, offline: offline) + } else if !recording && grows { + let canonical = try session.lockedGitTree(prior, offline: offline) + for resource in prior.resources.values.sorted(by: { $0.path < $1.path }) { + try prior.verify(resource, in: canonical, authenticatingSupportFrom: canonical) + } + } + } + let pair = pin.resources.sorted(by: { $0.key < $1.key }) + if let existing, !recording && !grows { + try session.verifyRetainedGitTree(pin, in: existing, offline: offline) + for (id, _) in pair { trees[id] = (pin, existing) } + continue + } + func verifying(_ tree: URL, support: URL?) throws -> URL { + for (_, resource) in pair { + try pin.verify(resource, in: tree, authenticatingSupportFrom: support) + } + return tree + } + let canonical: URL + do { + canonical = + try (pin.needsSupportAuthentication ? nil : borrowed?.borrowedGitTree(pin)) + ?? session.lockedGitTree(pin, offline: offline) + } catch let context as UnverifiableGitArchive { + do { + let historical = try session.lockedGitTree(pin, offline: offline, historical: true) + _ = try verifying(historical, support: historical) + for (id, _) in pair { trees[id] = (pin, historical) } + } catch { throw context } + continue + } + let tree: URL + do { + tree = try verifying(canonical, support: canonical) + } catch let error as CoreError { + guard case .invalidState = error else { throw error } + // Historical substitution requires covering locked hashes for external support. + let historical = try session.lockedGitTree(pin, offline: offline, historical: true) + do { + tree = try verifying(historical, support: historical) + } catch { throw error } + } + for (id, _) in pair { trees[id] = (pin, tree) } + } for (id, resource) in ledger.resources.sorted(by: { $0.key < $1.key }) where resourceIDs.contains(id) { try Task.checkCancellation() let file: URL - var snapshotRoot: URL? + let snapshotRoot: URL? if resource.kind == .liveEdit { file = try LedgerResources.liveEditSource(resource, ledger: ledger, roots: roots).authored + snapshotRoot = nil } else if resource.kind == .embedded || resource.kind == .artifact { if !completeSourceAdmission, let artifact = resource.artifact { for origin in EffectiveSourcePolicy.artifactOrigins(artifact) { @@ -317,92 +396,52 @@ package enum LedgerReplay { try store.environment.sourceAccess.requireDirectHTTP(url) } } - file = try materialize( + (file, snapshotRoot) = try materialize( resource, objects: ledger.contentObjects, in: workspace, preserveSpelling: anchorLockedGit) - } else { - var sourceID = resource.source - while let parent = ledger.sources[sourceID]?.container { sourceID = parent } - let source = ledger.sources[sourceID]! - let identity = try ledger.sourceIdentity(sourceID, roots: roots) - let cache = SourceCache( - store: store, sourcePolicy: sourcePolicy, - requireRecordedTransport: requireRecordedTransport, - acquisitions: session.acquisitions) - let declaration: SourceDeclaration - if let transport = source.transport { - declaration = SourceDeclaration( - kind: .git, location: transport, requirement: .revision(source.revision)) - } else if let location = source.location { - declaration = SourceDeclaration( - kind: .local, location: try location.resolve(roots: roots).path, - requirement: .revision(source.revision)) - } else { - throw CoreError.invalidState("missing pinned source coordinates") - } - if source.archive == nil { try cache.requireGit(declaration) } - let view: SourceSnapshot - let verifySupport = offline && observeResource != nil && !resource.support.isEmpty - if let archive = source.archive { - view = try session.snapshot( - declaration, - at: .init(revision: source.revision, version: source.version, archive: archive), - offline: offline) - } else if (offline || resource.support.isEmpty) && !verifySupport, - let tree = try cache.existingPinnedTree(sourceID: identity, revision: source.revision) - { - view = try SourceSnapshot( - snapshot: .init(source: identity, revision: source.revision), pin: nil, root: tree) - } else if offline { - let tree = try cache.withOfflineSnapshot( - sourceID: identity, source: LockedSource(kind: source.kind, url: source.transport), - revision: source.revision, useMaterializedTree: !verifySupport, - lockedPaths: anchorLockedGit - ? [resource.path] + resource.support.filter { $0.kind != .directory }.map(\.path) - : nil - ) { tree, durable in - if durable { return tree } - let copy = workspace.appendingPathComponent(UUID().uuidString) - try FileManager.default.moveItem(at: tree, to: copy) - return copy - } - view = try SourceSnapshot( - snapshot: .init(source: identity, revision: source.revision), pin: nil, root: tree) - } else { - view = try session.snapshot(declaration, at: SourceRevision(revision: source.revision)) - } - snapshotRoot = view.root + } else if let (pin, tree) = trees[id] { if anchorLockedGit { - let captured = try LedgerResources.captureLockedGit(resource, snapshotRoot: view.root) + let captured = try LedgerResources.captureLockedGit(resource, snapshotRoot: tree) var frozen = resource frozen.kind = .embedded frozen.entries = captured.entries frozen.support = captured.support - file = try materialize( + (file, snapshotRoot) = try materialize( frozen, objects: captured.objects, in: workspace, preserveSpelling: true) } else { - file = try view.resource(resource.path) + file = try pin.file(resource, in: tree) + snapshotRoot = tree } + } else { + let source = try ledger.rootSource(resource.source) + guard let archive = source.archive, let transport = source.transport else { + throw CoreError.invalidState("missing pinned archive coordinates") + } + let view = try session.snapshot( + .init(kind: .git, location: transport), + at: .init(revision: source.revision, version: source.version, archive: archive), + offline: offline) + snapshotRoot = view.root + file = try view.resource(resource.path) } - if resource.kind != .liveEdit - && !(anchorLockedGit && resource.kind == .git) - && !(offline && observeResource != nil && resource.kind == .git) - { + if resource.kind != .liveEdit && resource.kind != .git { + let verificationRoot = resource.kind == .archive ? snapshotRoot : nil let captured = try LedgerResources.capture( - file, embed: false, limits: limits, sourceRoot: snapshotRoot) + file, embed: false, limits: limits, sourceRoot: verificationRoot) let expected = resource.entries.map { entry -> LedgerEntry in var entry = entry entry.object = nil return entry } guard captured.hash == resource.hash, captured.entries == expected, - snapshotRoot == nil || captured.support == resource.support + verificationRoot == nil || captured.support == resource.support else { throw CoreError.invalidState("locked resource content or execute bits changed") } } try observeResource?(id, file, snapshotRoot) acquired[id] = file + snapshotRoots[id] = snapshotRoot } var result: [ReplayedArtifact] = [] var sealed: [LockedLowering] = [] @@ -444,14 +483,15 @@ package enum LedgerReplay { sealed.append(locked) result += rendered } - return try body(result, sealed, acquired, workspace) + return try body( + result, sealed, .init(files: acquired, snapshotRoots: snapshotRoots), workspace) } } private static func materialize( _ resource: LedgerResource, objects: [String: Data], in workspace: URL, preserveSpelling: Bool - ) throws -> URL { + ) throws -> (URL, URL?) { var embedded = resource embedded.kind = .embedded let name = UUID().uuidString @@ -471,8 +511,8 @@ package enum LedgerReplay { } else { try LedgerResources.materialize(embedded, objects: objects, at: destination) } - return resource.support.isEmpty - ? destination : try PathSafety.resolvedChild(base: destination, subpath: resource.path) + if resource.support.isEmpty { return (destination, nil) } + return (try PathSafety.resolvedChild(base: destination, subpath: resource.path), destination) } private static func skill( diff --git a/Sources/Components/PluginExpansion.swift b/Sources/Components/PluginExpansion.swift index c51ab81..09dec5c 100644 --- a/Sources/Components/PluginExpansion.swift +++ b/Sources/Components/PluginExpansion.swift @@ -25,7 +25,7 @@ extension Expansion { view = try selectedView(address, key: componentKey) } let container = try view.relativePath( - PathSafety.resolvedChild(base: view.directory(), subpath: path)) + PathSafety.resolvedChild(base: view.directory(requiringContents: false), subpath: path)) let recipients = condition.recipients( requested: agents ?? context.declaration.defaultAgents, scope: linking.store.scope, platform: linking.platform) @@ -45,6 +45,7 @@ extension Expansion { guard entries.count == 1, let (profile, document) = entries.first else { throw LinkError.invalid("plugin requires one supported native container manifest", chain) } + _ = try view.resource(container, recursive: true) let proposal = try SourceImport.preview( .init(profile: profile, root: view.root, document: document)) if let failure = proposal.diagnostics.first(where: { @@ -204,7 +205,8 @@ extension Expansion { } return try ResourceDeclaration( path: view.relativePath( - PathSafety.resolvedChild(base: view.directory(), subpath: value.path))) + PathSafety.resolvedChild( + base: view.directory(requiringContents: false), subpath: value.path))) } func run(_ value: ExecutableDeclaration) throws -> ExecutableDeclaration { var value = value @@ -281,7 +283,9 @@ enum PluginManifestSelection { (.geminiExtensionV1, "gemini-extension.json"), ] { let relative = path(suffix) - if FileManager.default.fileExists(atPath: try view.resource(relative).path) { + if FileManager.default.fileExists( + atPath: try view.resource(relative, recursive: false, optional: true).path) + { entries.append((profile, relative)) } } diff --git a/Sources/Components/SourceCatalog.swift b/Sources/Components/SourceCatalog.swift index 66c4400..d778027 100644 --- a/Sources/Components/SourceCatalog.swift +++ b/Sources/Components/SourceCatalog.swift @@ -266,10 +266,13 @@ package struct SourceCatalog: Sendable { label: label("Instruction", instruction.name), origin: .init(document: instruction.path, pointer: "")) } + let discovery = try view.directory(requiringContents: false) let manifest = try view.relativePath( - view.directory().appendingPathComponent( - view.directory().lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml")) - if FileManager.default.fileExists(atPath: try view.resource(manifest).path) { + discovery.appendingPathComponent( + discovery.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml")) + if FileManager.default.fileExists( + atPath: try view.resource(manifest, recursive: false, optional: true).path) + { let document = try DeclarationDocument( bytes: Array("version: 1\n".utf8), identity: .init("catalog/agents.yaml")) let linker = Linking( diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index 593ab2d..8e06a7d 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -9,8 +9,7 @@ import Testing @Suite("Durable cache publication") struct CachePublicationTests { @Test( - arguments: ["cache-content", "cache-git"], - [ + arguments: [ TransactionCheckpoint.copy( 0, .init(path: TransactionSlot.staged.name(0), step: .directoryCreated) ).name, @@ -20,9 +19,9 @@ struct CachePublicationTests { TransactionCheckpoint.publication(0, .created).name, TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, ]) - func interruptedTreePublicationRecoversAndRetries(_ kind: String, _ point: String) throws { - let fixture = try CacheFixture(git: kind == "cache-git") - try interrupt(fixture, kind: kind, point: point) + func interruptedTreePublicationRecoversAndRetries(_ point: String) throws { + let fixture = try CacheFixture() + try interrupt(fixture, kind: "cache-content", point: point) let committed = point == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name if committed || point == TransactionCheckpoint.publication(0, .created).name { #expect(try FileHash.folderHash(fixture.destination) == fixture.hash) @@ -65,26 +64,6 @@ struct CachePublicationTests { #expect(try Data(contentsOf: fixture.store.resolvedURL) == fixture.lockBytes) } - @Test(arguments: [ - TransactionCheckpoint.stage(0, .workCreated).name, - TransactionCheckpoint.stage(0, .workPrepared).name, - ]) - func interruptedExtractionCleansJournalOwnedWork(_ point: String) throws { - let fixture = try CacheFixture(git: true) - try interrupt(fixture, kind: "cache-git", point: point) - #expect(try FileSnapshot.read(at: fixture.destination) == nil) - #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.withLock {} - } - #expect( - try FileManager.default.contentsOfDirectory( - atPath: fixture.destination.deletingLastPathComponent().path - ).isEmpty) - try fixture.publish() - #expect(try FileHash.folderHash(fixture.destination) == fixture.hash) - #expect(try Data(contentsOf: fixture.store.resolvedURL) == fixture.lockBytes) - } - @Test func verifiesPrivateCopyBeforePublication() throws { let fixture = try CacheFixture() let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) @@ -192,10 +171,7 @@ private final class CacheFixture { let digest: String let destination: URL let lockBytes: Data - private let sourceID: String - private let revision: String? - - init(git: Bool = false) throws { + init() throws { root = try temporaryDirectory() do { let tree = root.appendingPathComponent("new") @@ -212,41 +188,15 @@ private final class CacheFixture { environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:])) - let source: LockedSource - let skill: LockedSkill - let cache = SourceCache(store: store) - if git { - try initGitRepo(tree) - revision = try gitHead(tree) - sourceID = "local:" + tree.path - source = LockedSource(kind: .local) - skill = LockedSkill( - source: sourceID, revision: revision, path: ".", hash: "sha256:" + hash, - installs: ["codex": .link]) - destination = cache.materializedURL(sourceID: sourceID, revision: revision!) - } else { - revision = nil - sourceID = "https://example.test" - source = LockedSource(kind: .wellKnown) - skill = LockedSkill( - source: sourceID, - artifact: LockedArtifact( - type: .archive, url: sourceID + "/archive.tar.gz", digest: digest), - hash: "sha256:" + hash, installs: ["codex": .link]) - destination = store.cacheDirectory.appendingPathComponent( - "artifact-content/" + digest.dropFirst(7)) - } + let source = "https://example.test" + let artifact = LockedArtifact(type: .archive, url: source + "/archive.tar.gz", digest: digest) + destination = store.cacheDirectory.appendingPathComponent( + "artifact-content/" + digest.dropFirst(7)) var ledger = ResolvedLedger() - ledger.sources["source"] = LedgerSource( - kind: source.kind, - transport: source.kind == .wellKnown ? sourceID : source.url, - location: source.kind == .local - ? .init(kind: .absolute, path: String(sourceID.dropFirst(6))) : nil, - revision: revision ?? digest) + ledger.sources["source"] = LedgerSource(kind: .wellKnown, transport: source, revision: digest) ledger.resources["resource"] = LedgerResource( - kind: revision == nil ? .artifact : .git, - source: "source", path: ".", hash: skill.hash!, - entries: [.init(path: ".", kind: .directory, executable: false)], artifact: skill.artifact) + kind: .artifact, source: "source", path: ".", hash: "sha256:" + hash, + entries: [.init(path: ".", kind: .directory, executable: false)], artifact: artifact) try store.save(declaration: Declaration(), ledger: ledger) lockBytes = try Data(contentsOf: store.resolvedURL) } catch { @@ -259,13 +209,8 @@ private final class CacheFixture { func publish() throws { let cache = SourceCache(store: store) try store.withLock { - if let revision { - _ = try cache.materialize( - sourceID: sourceID, source: LockedSource(kind: .local), revision: revision) - } else { - _ = try cache.materializeArtifact( - root.appendingPathComponent("new"), digest: digest, hash: "sha256:" + hash) - } + _ = try cache.materializeArtifact( + root.appendingPathComponent("new"), digest: digest, hash: "sha256:" + hash) } } } diff --git a/Tests/AgentsCoreTests/GitErrorTests.swift b/Tests/AgentsCoreTests/GitErrorTests.swift index 7fd5b81..3093b2d 100644 --- a/Tests/AgentsCoreTests/GitErrorTests.swift +++ b/Tests/AgentsCoreTests/GitErrorTests.swift @@ -361,7 +361,7 @@ struct GitErrorTests { #expect(error.description == "Git could not clone https://example.com/source.git.") } - @Test func gitChildrenDisablePromptsAndPreserveCallerEnvironment() throws { + @Test func gitChildrenDisablePromptsAndUseTheEnvironmentForTheirTransport() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } let upstream = root.appendingPathComponent("source") @@ -374,28 +374,37 @@ struct GitErrorTests { try Data( """ #!/bin/sh - printf '%s|%s|%s|%s\\n' "$GIT_TERMINAL_PROMPT" "$GCM_INTERACTIVE" \ - "$GIT_TEST_SENTINEL" "$SSH_AUTH_SOCK" >> "$GIT_TEST_LOG" + root=${0%/bin/git} + printf '%s|%s|%s|%s|%s|%s\\n' "$GIT_TERMINAL_PROMPT" "$GCM_INTERACTIVE" \ + "$GIT_TEST_SENTINEL" "$SSH_AUTH_SOCK" "$GIT_CONFIG_GLOBAL" "$GIT_ALLOW_PROTOCOL" \ + >> "$root/git-environment.log" exec /usr/bin/git "$@" """.utf8 ).write(to: git) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: git.path) let log = root.appendingPathComponent("git-environment.log") + let config = root.appendingPathComponent("git-global-config") + try Data().write(to: config) let process = try stateTestProcess( root: root, arguments: ["git-environment"], environment: [ "PATH": bin.path + ":" + (ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin"), "GIT_TERMINAL_PROMPT": "1", "GCM_INTERACTIVE": "always", "GIT_TEST_SENTINEL": "preserved", "SSH_AUTH_SOCK": "fixture-socket", - "GIT_TEST_LOG": log.path, + "GIT_CONFIG_GLOBAL": config.path, "GIT_ALLOW_PROTOCOL": "file:ssh", ]) process.waitUntilExit() #expect(process.terminationStatus == 0) - let lines = try String(contentsOf: log, encoding: .utf8).split(separator: "\n") - // Clone/fetch hold a mirror lock; local inspection uses Foundation.Process. - #expect(lines.count >= 12) - #expect(lines.allSatisfy { $0 == "0|never|preserved|fixture-socket" }) + let lines = try String(contentsOf: log, encoding: .utf8).split(separator: "\n").map(String.init) + let inherited = "0|never|preserved|fixture-socket|\(config.path)|" + let plumbing = "0||||/dev/null|" + let advertisement = "0||||/dev/null|file" + #expect(lines.contains(inherited + "file:ssh")) + #expect(lines.contains(plumbing)) + #expect(lines.contains(advertisement)) + let expected: Set = [inherited, inherited + "file:ssh", plumbing, advertisement] + #expect(Set(lines).subtracting(expected).isEmpty) } private func expectConcise( diff --git a/Tests/AgentsCoreTests/LedgerRetentionTests.swift b/Tests/AgentsCoreTests/LedgerRetentionTests.swift index 8feff32..aa19193 100644 --- a/Tests/AgentsCoreTests/LedgerRetentionTests.swift +++ b/Tests/AgentsCoreTests/LedgerRetentionTests.swift @@ -10,14 +10,8 @@ struct LedgerRetentionTests { defer { removeTemporaryDirectory(root) } let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) try FileSystem.createDirectory(at: store.directory) - let cache = SourceCache(store: store) let source = "github.com/example/components" let pin = String(repeating: "a", count: 40) - let obsolete = String(repeating: "b", count: 40) - let kept = cache.materializedURL(sourceID: source, revision: pin) - let unused = cache.materializedURL(sourceID: source, revision: obsolete) - try FileSystem.createDirectory(at: kept) - try FileSystem.createDirectory(at: unused) var ledger = ResolvedLedger() ledger.sources["group-source"] = LedgerSource( kind: .git, @@ -28,26 +22,15 @@ struct LedgerRetentionTests { manifestHash: "sha256:" + String(repeating: "c", count: 64), children: []) ] var references = try RetentionReferences(ledger: ledger, roots: [:]) - #expect(references.git.count == 1) - let tx = FileTransaction(store: store) - try cache.prune(references: references, transaction: tx) - #expect(FileManager.default.fileExists(atPath: unused.path)) - try tx.commit() - #expect(FileManager.default.fileExists(atPath: kept.path)) - #expect(!FileManager.default.fileExists(atPath: unused.path)) - ledger.groups = [] - ledger.sources = [:] - references = try RetentionReferences(ledger: ledger, roots: [:]) - try references.include( - watch: WatchState(sources: [source: WatchSourceState(seen: .revision(pin))])) - let watched = FileTransaction(store: store) - try cache.prune(references: references, transaction: watched) - try watched.commit() - #expect(FileManager.default.fileExists(atPath: kept.path)) - let released = FileTransaction(store: store) - try cache.prune(references: RetentionReferences(), transaction: released) - try released.commit() - #expect(!FileManager.default.fileExists(atPath: kept.path)) + #expect(references.requiredGitObjects == [.init(source: source, revision: pin)]) + #expect(references.protectedGitRefs == references.requiredGitObjects) + let watched = String(repeating: "c", count: 40) + try references.include(watch: WatchState(sources: [source: .init(seen: .revision(watched))])) + #expect( + references.requiredGitObjects == [ + .init(source: source, revision: pin), .init(source: source, revision: watched), + ]) + } @Test func danglingAncestryAndReferencesReject() throws { diff --git a/Tests/AgentsCoreTests/PinTransactionAdmissionTests.swift b/Tests/AgentsCoreTests/PinTransactionAdmissionTests.swift new file mode 100644 index 0000000..fc75d6e --- /dev/null +++ b/Tests/AgentsCoreTests/PinTransactionAdmissionTests.swift @@ -0,0 +1,441 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Pin transaction admission", .serialized) +struct PinTransactionAdmissionTests { + @Test func streamingEvidenceMatchesBufferedSnapshot() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let tree = root.appendingPathComponent("tree") + try FileManager.default.createDirectory(at: tree, withIntermediateDirectories: false) + try Data("content".utf8).write(to: tree.appendingPathComponent("file")) + try FileManager.default.createSymbolicLink( + atPath: tree.appendingPathComponent("link").path, withDestinationPath: "file") + let parent = try DirectoryHandle(at: root) + let snapshot = try #require(try FileSnapshot.read("tree", from: parent)) + #expect(try FileSnapshot.read("tree", from: parent, streaming: snapshot.identity) == snapshot) + } + + @Test func retiresAnOrdinaryPinWithAFileLargerThanTheBufferedLimit() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + let pin = SourceCache(store: store).materializedURL( + sourceID: "local:/fixture", revision: String(repeating: "a", count: 40)) + try FileManager.default.createDirectory(at: pin, withIntermediateDirectories: true) + try sparseFile( + at: pin.appendingPathComponent("large"), + bytes: UInt64(LedgerLimits.standard.resourceBytes) + 1) + #expect(throws: CoreError.self) { try TargetPrecondition(pin) } + let expected = try TargetPrecondition(materializedPin: pin, store: store) + #expect(expected.exists) + let transaction = FileTransaction(store: store) + try transaction.delete(pin, expecting: expected) + try transaction.commit() + #expect(!FileManager.default.fileExists(atPath: pin.path)) + } + + @Test(arguments: [false, true]) + func preparedExchangeHasOnlyOneTerminalSlot(_ undo: Bool) throws { + var limits = LedgerLimits.standard + limits.resourceBytes = 128 * 1024 + try FileSnapshot.$captureLimits.withValue(limits) { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: false) + try sparseFile(at: store.resolvedURL, bytes: 70 * 1024) + let original = try FileSnapshot.read(at: store.resolvedURL) + var reached = false + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.progress(0, .ready).name { + let folder = try #require( + FileManager.default.contentsOfDirectory(atPath: store.directory.path).first { + $0.hasPrefix(".agents-") + }) + let names = try FileManager.default.contentsOfDirectory( + atPath: store.directory.appendingPathComponent(folder).path) + #expect(names == [TransactionSlot.exchanged.name(0)]) + } + if undo && point == TransactionCheckpoint.commitValidated.name { + reached = true + throw CoreError.invalidState("interrupt before commit") + } + } + try transaction.replace( + store.resolvedURL, + with: .prepared { workspace in + let file = workspace.appendingPathComponent("replacement") + try sparseFile(at: file, bytes: 70 * 1024, prefix: 42) + return file + }) + if undo { + #expect(throws: CoreError.invalidState("interrupt before commit")) { + try transaction.commit() + } + #expect(reached) + #expect(try FileSnapshot.read(at: store.resolvedURL) == original) + } else { + try transaction.commit() + #expect(try FileSnapshot.read(at: store.resolvedURL)?.digest != original?.digest) + } + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path)) + } + } + + @Test func jointlyOversizedDisposalSlotsFailBeforePublishing() throws { + var limits = LedgerLimits.standard + limits.resourceBytes = 128 * 1024 + try FileSnapshot.$captureLimits.withValue(limits) { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: false) + let payload = root.appendingPathComponent("payload") + try sparseFile(at: payload, bytes: 70 * 1024) + var beganPublishing = false + let transaction = FileTransaction(store: store) { point in + if point.hasPrefix("publish.") { beganPublishing = true } + } + try transaction.replace(store.declarationURL, with: .copy(payload)) + try transaction.replace(store.resolvedURL, with: .copy(payload)) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(!beganPublishing) + #expect(!FileManager.default.fileExists(atPath: store.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: store.resolvedURL.path)) + } + } + + @Test func rollbackPreservesMultipleExternallyChangedTargets() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: false) + let targets = [store.declarationURL, store.resolvedURL, store.watchURL] + for target in targets { try sparseFile(at: target, bytes: 42 * 1024) } + var limits = LedgerLimits.standard + limits.resourceBytes = 128 * 1024 + var recordedConflicts = 0 + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.commitValidated.name { + for target in targets { try Data("outside change".utf8).write(to: target) } + throw CoreError.invalidState("interrupt before commit") + } + if point.hasPrefix("recovery.journal.applying.entry."), + point.hasSuffix(".conflict.renamed") + { + recordedConflicts += 1 + } + } + for target in targets { try transaction.replace(target, with: .data(Data("new".utf8))) } + #expect(throws: CoreError.self) { + try FileSnapshot.$captureLimits.withValue(limits) { try transaction.commit() } + } + let bytes = try Data(contentsOf: store.directory.appendingPathComponent("transaction.json")) + try LedgerAdmission.check(bytes, limits: .standard) + let journal = try JSONDecoder().decode(TransactionJournal.self, from: bytes) + #expect(journal.entries.filter { $0.conflict != nil }.count == 3) + #expect(recordedConflicts == 3) + for target in targets { #expect(try Data(contentsOf: target) == Data("outside change".utf8)) } + } + + @Test func disposalIntentEditPreservesEveryDisplacedSibling() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + let pin = SourceCache(store: store).materializedURL( + sourceID: "local:/fixture", revision: String(repeating: "a", count: 40)) + try FileManager.default.createDirectory(at: pin, withIntermediateDirectories: true) + let first = Data("first".utf8) + try first.write(to: pin.appendingPathComponent("a-first")) + try Data("original".utf8).write(to: pin.appendingPathComponent("z-last")) + let journalURL = store.directory.appendingPathComponent(TransactionJournal.fileName) + let edited = Data("external".utf8) + var displaced: URL? + let outcome = TransactionOutcome() + let transaction = FileTransaction(store: store, outcome: outcome) { point in + if point == TransactionCheckpoint.disposalIntent.name { + let journal = try FileTransaction.readJournal(Data(contentsOf: journalURL)) + let container = pin.deletingLastPathComponent().appendingPathComponent( + journal.containers[journal.entries[0].container].name) + let moved = container.appendingPathComponent(TransactionSlot.deleted.name(0)) + try edited.write(to: moved.appendingPathComponent("z-last")) + displaced = moved + } + } + try transaction.delete(pin, expecting: TargetPrecondition(materializedPin: pin, store: store)) + #expect(throws: CoreError.self) { try transaction.commit() } + let moved = try #require(displaced) + #expect(try Data(contentsOf: moved.appendingPathComponent("a-first")) == first) + #expect(try Data(contentsOf: moved.appendingPathComponent("z-last")) == edited) + #expect(outcome.terminal == .committed && outcome.recoveryPending) + let journal = try FileTransaction.readJournal(Data(contentsOf: journalURL)) + #expect(journal.disposing && journal.entries[0].conflict != nil) + } + + @Test(arguments: [false, true]) + func equivalentDeferredLedgerKeepsItsPreimageDuringCommitAndRollback(_ undo: Bool) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: false) + try Data("ledger".utf8).write(to: store.resolvedURL) + let original = try TargetPrecondition(store.resolvedURL) + var skipped = false + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.progress(1, .skipped).name { skipped = true } + if undo && point == TransactionCheckpoint.commitValidated.name { + throw CoreError.invalidState("interrupt before commit") + } + } + try transaction.replace(store.declarationURL, with: .data(Data("declaration".utf8))) + try transaction.stageResolvedLedger(expecting: original) { nil } + if undo { + #expect(throws: CoreError.invalidState("interrupt before commit")) { + try transaction.commit() + } + } else { + try transaction.commit() + } + #expect(skipped) + #expect(try FileSnapshot.read(at: store.resolvedURL) == original.snapshot) + #expect(FileManager.default.fileExists(atPath: store.declarationURL.path) == !undo) + } + + @Test(arguments: ["sealing", "commit marker", "committed recovery"]) + func skippedLedgerDetectsAnExternalReplacement(_ boundary: String) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: false) + try Data("ledger".utf8).write(to: store.resolvedURL) + let original = try TargetPrecondition(store.resolvedURL) + let outcome = TransactionOutcome() + let injection = + switch boundary { + case "sealing": TransactionCheckpoint.progress(1, .applied).name + case "commit marker": TransactionCheckpoint.persisted(.committed, .terminal, .written).name + default: TransactionCheckpoint.phase(.committed).name + } + let replacement = Data("external ledger".utf8) + var injected = false + let transaction = FileTransaction(store: store, outcome: outcome) { point in + guard point == injection else { return } + try replacement.write(to: store.resolvedURL, options: .atomic) + injected = true + if boundary == "committed recovery" { throw CoreError.invalidState("interrupt cleanup") } + } + try transaction.stageResolvedLedger(expecting: original) { nil } + try transaction.replace(store.declarationURL, with: .data(Data("declaration".utf8))) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(injected) + #expect(try Data(contentsOf: store.resolvedURL) == replacement) + let journalURL = store.directory.appendingPathComponent("transaction.json") + if boundary == "committed recovery" { + let journal = try FileTransaction.readJournal(Data(contentsOf: journalURL)) + #expect(journal.phase == .committed && journal.entries[0].conflict != nil) + #expect(outcome.recoveryPending) + } else { + #expect(outcome.terminal == .rolledBack) + #expect(!FileManager.default.fileExists(atPath: store.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: journalURL.path)) + } + } + + @Test func encodedJournalAdmissionRejectsBeforePublishing() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: false) + let original = Data("original".utf8) + try original.write(to: store.declarationURL) + var limits = LedgerLimits.standard + limits.encodedBytes = 4_096 + var ready = false + var published = false + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.preconditions.name { + let bytes = try Data(contentsOf: store.directory.appendingPathComponent("transaction.json")) + try LedgerAdmission.check(bytes, limits: limits) + let journal = try FileTransaction.readJournal(bytes) + #expect(journal.phase == .preparing && journal.entries[0].progress == .ready) + ready = true + } + if point.hasPrefix("publish.") { published = true } + } + try transaction.replace(store.declarationURL, with: .data(Data("replacement".utf8))) + #expect(throws: CoreError.invalidState("ledger encoding or byte budget")) { + try transaction.commit(journalAdmissionLimits: limits) + } + #expect(ready && !published) + #expect(try Data(contentsOf: store.declarationURL) == original) + } + + @Test func rollbackPersistsBoundedMultibyteConflict() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: false) + let reason = String(repeating: "é界🙂", count: 300) + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.commitValidated.name { + throw CoreError.invalidState("interrupt before commit") + } + if point == "recovery." + TransactionCheckpoint.restoration(0, .validated).name { + throw CoreError.invalidState(reason) + } + } + try transaction.replace(store.declarationURL, with: .data(Data("replacement".utf8))) + #expect(throws: CoreError.self) { try transaction.commit() } + let bytes = try Data(contentsOf: store.directory.appendingPathComponent("transaction.json")) + let journal = try FileTransaction.readJournal(bytes) + let persisted = try #require(journal.entries[0].conflict?.reason) + #expect(persisted.utf8.count <= TransactionJournal.Conflict.reasonBytes) + #expect(persisted.utf8.count > 1_000 && persisted.contains("é界🙂")) + } + + @Test func admittedNearLimitJournalPersistsBothRollbackConflicts() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: false) + let targets = [store.declarationURL, store.resolvedURL] + for target in targets { try Data("original".utf8).write(to: target) } + var limits = LedgerLimits.standard + limits.encodedBytes = 17 * 1024 + let reason = String(repeating: "\u{0}", count: TransactionJournal.Conflict.reasonBytes) + let journalURL = store.directory.appendingPathComponent(TransactionJournal.fileName) + var reachedCommitValidation = false + var persisted = 0 + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.commitValidated.name { + reachedCommitValidation = true + throw CoreError.invalidState("interrupt before commit") + } + if targets.indices.contains(where: { + point == "recovery." + TransactionCheckpoint.restoration($0, .validated).name + }) { + throw CoreError.invalidState(reason) + } + if point.hasPrefix("recovery.journal.applying.entry."), point.hasSuffix(".conflict.renamed") { + try LedgerAdmission.check(Data(contentsOf: journalURL), limits: limits) + persisted += 1 + } + } + for target in targets { try transaction.replace(target, with: .data(Data("next".utf8))) } + #expect(throws: CoreError.self) { try transaction.commit(journalAdmissionLimits: limits) } + try #require(reachedCommitValidation) + let bytes = try Data(contentsOf: journalURL) + try LedgerAdmission.check(bytes, limits: limits) + #expect(limits.encodedBytes - bytes.count < 3 * 1024) + let journal = try FileTransaction.readJournal(bytes) + #expect(journal.phase == .applying) + #expect(journal.entries.compactMap(\.conflict).count == targets.count) + #expect(persisted == targets.count) + } + + @Test func materializedPinRequiresTheEntireObjectID() { + let prefix = "state/cache/materialized/fixture-" + String(repeating: "b", count: 64) + "/" + let oid = String(repeating: "a", count: 40) + #expect(TransactionPaths.isMaterializedPin(prefix + oid)) + #expect(!TransactionPaths.isMaterializedPin(prefix + oid + "\n")) + } + + @Test func slotDepthAndSurvivingDirectoryModeAreChecked() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + let pin = SourceCache(store: store).materializedURL( + sourceID: "local:/fixture", revision: String(repeating: "b", count: 40)) + var last = pin + for _ in 0..<31 { last.appendPathComponent("depth") } + try FileManager.default.createDirectory(at: last, withIntermediateDirectories: true) + let evidence = try TargetPrecondition(materializedPin: pin, store: store) + var beganPublishing = false + let transaction = FileTransaction(store: store) { point in + if point.hasPrefix("publish.") { beganPublishing = true } + } + try transaction.delete(pin, expecting: evidence) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(!beganPublishing) + #expect(FileManager.default.fileExists(atPath: last.path)) + let directory = try DirectoryHandle(at: root) + try directory.makeDirectory("modes") + let initial = try #require(try FileSnapshot.read("modes", from: directory)) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: root.appendingPathComponent("modes").path) + let edited = try #require(try FileSnapshot.read("modes", from: directory)) + #expect(!initial.containsRemaining(edited)) + } + + private func fixtureStore(_ root: URL) -> StateStore { + StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + } + + private func sparseFile(at url: URL, bytes: UInt64, prefix: UInt8 = 0) throws { + try Data([prefix]).write(to: url) + let file = try FileHandle(forWritingTo: url) + defer { try? file.close() } + try file.truncate(atOffset: bytes) + } +} + +extension PinTransactionAdmissionTests { + @Test func ordinaryPinIsTheOnlyStreamingPreimageRole() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = fixtureStore(root) + let pin = SourceCache(store: store).materializedURL( + sourceID: "local:/fixture", revision: String(repeating: "a", count: 40)) + try FileManager.default.createDirectory(at: pin, withIntermediateDirectories: true) + let target = try TargetPrecondition(materializedPin: pin, store: store) + let original = try #require(target.snapshot) + let logical = try TransactionPaths(store: store).path(for: pin) + var entry = TransactionJournal.Entry( + path: logical, action: .delete, preimage: original, parentIdentity: "", container: 0) + #expect(entry.streamingPreimage == original.identity) + entry.path = "state/cache/materialized/" + pin.lastPathComponent + #expect(entry.streamingPreimage == nil) + entry.path = logical + entry.security.preimage = .privateMaterialization + #expect(entry.streamingPreimage == nil) + entry.security.preimage = .ordinary + entry.security.preimageAccess = try DirectoryHandle(at: pin).accessEvidence() + #expect(entry.streamingPreimage == nil) + entry.security.preimageAccess = nil + entry.security.preimageTreeAccess = [] + #expect(entry.streamingPreimage == nil) + } + + @Test(arguments: [true, false]) + func streamingReadRejectsChangedFileGeneration(_ grows: Bool) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let url = root.appendingPathComponent("large") + let size = 128 * 1024 + try sparseFile(at: url, bytes: UInt64(size)) + let parent = try DirectoryHandle(at: root) + let stat = try #require(try parent.info("large")) + let file = try FileHandle(forWritingTo: url) + defer { try? file.close() } + var wrote = false + #expect(throws: CoreError.self) { + try parent.readChunks("large", matching: stat, maximumBytes: size) { _ in + if !wrote { + wrote = true + try file.truncate(atOffset: UInt64(grows ? size + 1 : 1)) + } + } + } + #expect(wrote) + } +} diff --git a/Tests/AgentsCoreTests/RequirementSemanticsTests.swift b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift index ab41317..a412f14 100644 --- a/Tests/AgentsCoreTests/RequirementSemanticsTests.swift +++ b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift @@ -131,13 +131,13 @@ struct RequirementSemanticsTests { LockedSource.self, from: Data(#"{"kind":"local","requirement":{"from":"v1.2.0","to":"2.0.0"}}"#.utf8)) let newDescriptor = LockedSource(kind: .local, requirement: source.requirement) - let before = try cache.materialize( - sourceID: id, source: oldDescriptor, revision: first.0.revision) - let after = try cache.materialize( - sourceID: id, source: newDescriptor, revision: first.0.revision) - #expect(before == after) - #expect( - try String(contentsOf: after.appendingPathComponent("content"), encoding: .utf8) == "old") + func contents(_ descriptor: LockedSource) throws -> String { + try cache.withSnapshot(sourceID: id, source: descriptor, revision: first.0.revision) { + try String(contentsOf: $0.appendingPathComponent("content"), encoding: .utf8) + } + } + #expect(try contents(oldDescriptor) == contents(newDescriptor)) + #expect(try contents(newDescriptor) == "old") } } diff --git a/Tests/AgentsCoreTests/ScopeAdmissionAliasTests.swift b/Tests/AgentsCoreTests/ScopeAdmissionAliasTests.swift new file mode 100644 index 0000000..02adcce --- /dev/null +++ b/Tests/AgentsCoreTests/ScopeAdmissionAliasTests.swift @@ -0,0 +1,21 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Scope admission aliases") +struct ScopeAdmissionAliasTests { + @Test func createsProjectScopeThroughSystemTemporaryAlias() throws { + #if os(macOS) + let root = URL(fileURLWithPath: "/private/tmp/" + UUID().uuidString, isDirectory: true) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, environment: [:])) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: root) } + try store.withLock {} + #expect(FileManager.default.fileExists(atPath: store.directory.path)) + #endif + } +} diff --git a/Tests/AgentsCoreTests/ScopedGitArchiveTests.swift b/Tests/AgentsCoreTests/ScopedGitArchiveTests.swift new file mode 100644 index 0000000..afb9913 --- /dev/null +++ b/Tests/AgentsCoreTests/ScopedGitArchiveTests.swift @@ -0,0 +1,701 @@ +import Foundation +import StateTestSupport +import Synchronization +import Testing + +@testable import AgentsCore + +@Suite("Scoped Git archives") +struct ScopedGitArchiveTests { + @Test func expansionKeepsTraversedDirectoriesWithoutTheirChildren() throws { + let fixture = try Repository() + try fixture.write("observed", "real/file") + try fixture.write("unrelated", "bridge/omit") + try FileManager.default.createSymbolicLink( + atPath: fixture.repo.appendingPathComponent("alias").path, + withDestinationPath: "bridge/../real") + try fixture.commit() + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let pin = try #require(try session.candidates(for: fixture.source, requirements: [nil]).first) + let view = try session.snapshot(fixture.source, at: pin) + let root = try session.resource(snapshot: view.snapshot, path: ".") + #expect(try FileManager.default.contentsOfDirectory(atPath: root.path).isEmpty) + let file = try view.resource("alias/file") + #expect(try String(contentsOf: file, encoding: .utf8) == "observed") + #expect( + try FileManager.default.contentsOfDirectory( + atPath: root.appendingPathComponent("bridge").path + ).isEmpty) + let evidence = try LedgerResources.capture( + file, embed: false, limits: .standard, sourceRoot: root) + #expect(evidence.support.map(\.path) == ["alias", "bridge", "real"]) + let record = LedgerResource( + kind: .git, source: "fixture", path: "alias/file", hash: evidence.hash, + entries: evidence.entries, support: evidence.support) + #expect( + try Set(LedgerResources.validatedEntries(record).keys) == [ + ".", "alias", "bridge", "real", "real/file", + ]) + _ = try view.resource("bridge/omit", recursive: false) + #expect(try session.resource(snapshot: view.snapshot, path: ".") == root) + #expect(try String(contentsOf: file, encoding: .utf8) == "observed") + } + } + + @Test func archiveSubstitutionsUseFullOrderAndIgnoreTagAndProducerConfiguration() throws { + let fixture = try Repository() + try fixture.write("*.txt export-subst\nignored export-ignore\n", ".gitattributes") + for path in ["a.txt", "b.txt"] { + try fixture.write("$Format:%(describe:tags=true)$ $Format:%H$\n", path) + } + try fixture.write("not retained", "ignored") + try fixture.commit() + try fixture.git(["tag", "-a", "1.0.0", "-m", "one"]) + try fixture.write("*.txt export-ignore\n", ".git/info/attributes") + try fixture.git(["config", "tar.umask", "0777"]) + try fixture.write("uncommitted", "a.txt") + let revision = try fixture.git(["rev-parse", "HEAD"]) + let expected: [Data] = try SourceResolutionSession.withTemporaryRead(store: fixture.store) { + session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + _ = try view.directory() + #expect( + !FileManager.default.fileExists(atPath: view.root.appendingPathComponent("ignored").path)) + return try ["a.txt", "b.txt"].map { try Data(contentsOf: view.resource($0)) } + } + try fixture.git(["tag", "-d", "1.0.0"]) + try fixture.git(["tag", "2.0.0"]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + let a = try view.resource("a.txt") + #expect(try FileManager.default.contentsOfDirectory(atPath: view.root.path) == ["a.txt"]) + let b = try view.resource("b.txt") + #expect(try [Data(contentsOf: a), Data(contentsOf: b)] == expected) + } + } + + @Test func substitutesASCIIFormatsInBinaryBlobs() throws { + let fixture = try Repository() + try fixture.write("*.bin export-subst\n", ".gitattributes") + let prefix = Data([0xFF, 0]) + let suffix = Data([0xFE, 0]) + try (prefix + Data("$Format:%H$".utf8) + suffix).write( + to: fixture.repo.appendingPathComponent("binary.bin")) + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + let archived = try Data(contentsOf: view.resource("binary.bin")) + #expect(archived == prefix + Data(revision.utf8) + suffix) + } + } + + @Test(arguments: ["+", "-", " "]) + func modifiedDescribeUsesFullArchiveOrder(_ modifier: String) throws { + let fixture = try Repository() + try fixture.write("*.txt export-subst\n", ".gitattributes") + for path in ["a.txt", "b.txt"] { + try fixture.write("$Format:%\(modifier)(describe:tags=true)$\n", path) + } + try fixture.commit() + try fixture.git(["tag", "visible"]) + let revision = try fixture.git(["rev-parse", "HEAD"]) + let archive = GitTreeArchive( + repository: fixture.repo, workspace: fixture.root, revision: revision, + source: fixture.repo.path, lock: nil) + let full = fixture.root.appendingPathComponent("full") + let scoped = fixture.root.appendingPathComponent("scoped") + try archive.extract([.init(path: ".")], into: full) + try archive.extract([.init(path: "b.txt")], into: scoped) + let first = try String(contentsOf: full.appendingPathComponent("a.txt"), encoding: .utf8) + let second = try Data(contentsOf: full.appendingPathComponent("b.txt")) + #expect(first.contains("visible")) + #expect(!String(decoding: second, as: UTF8.self).contains("visible")) + #expect(try Data(contentsOf: scoped.appendingPathComponent("b.txt")) == second) + } + + @Test(arguments: ["%G?", "%GK", "%(unknown)", "%+%G?"]) + func contextualSubstitutionRejectsUncoveredSupport(_ format: String) throws { + let fixture = try Repository() + try fixture.write("support export-subst\n", ".gitattributes") + try fixture.write("$Format:\(format)$\n", "support") + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + let archive = GitTreeArchive( + repository: fixture.repo, workspace: fixture.root, revision: revision, + source: fixture.repo.path, lock: nil) + do { + try archive.extract( + [.init(path: "support", recursive: false)], + into: fixture.root.appendingPathComponent("extracted"), + uncoveredSupport: [Data("support".utf8)]) + Issue.record("Accepted contextual support without a covering hash") + } catch let error as UnverifiableGitArchive { + #expect(error.path == "support" && error.revision == revision) + } + } + + @Test func shortDatesAuthenticateUncoveredSupport() throws { + let fixture = try Repository() + try fixture.write("support export-subst\n", ".gitattributes") + try fixture.write("$Format:%as %cs %%G?$\n", "support") + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + let dates = try fixture.git(["show", "-s", "--format=%as %cs", revision]) + let archive = GitTreeArchive( + repository: fixture.repo, workspace: fixture.root, revision: revision, + source: fixture.repo.path, lock: nil) + let extracted = fixture.root.appendingPathComponent("extracted") + try archive.extract( + [.init(path: "support", recursive: false)], into: extracted, + uncoveredSupport: [Data("support".utf8)]) + #expect( + try String(contentsOf: extracted.appendingPathComponent("support"), encoding: .utf8) + == dates + " %G?\n") + } + + @Test func disposableCopiesPreserveContentsWithoutDurabilityBarriers() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let directory = try DirectoryHandle(at: root) + let tree = try directory.makeDirectory("origin") + try tree.write("executable", data: Data("contents".utf8), mode: 0o755) + let flushes = Mutex(0) + try DirectoryHandle.$synchronizationObserver.withValue( + .init(didSynchronize: { flushes.withLock { $0 += 1 } }) + ) { + try directory.copy("copy", from: directory, named: "origin", durable: false) + } + #expect(flushes.withLock { $0 } == 0) + #expect(try directory.child("copy").read("executable") == Data("contents".utf8)) + #expect((try directory.child("copy").info("executable")?.st_mode ?? 0) & 0o777 == 0o755) + } + + @Test func optionalSuffixRequiresTheDirectoryLinkToResolveFirst() throws { + let fixture = try Repository() + try fixture.write("fixture", "real/file") + try fixture.write("ignored export-ignore\n", ".gitattributes") + for (name, target) in [("alias", "real"), ("broken", "absent"), ("ignored", "real")] { + try FileManager.default.createSymbolicLink( + atPath: fixture.repo.appendingPathComponent(name).path, withDestinationPath: target) + } + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + let absent = try view.resource("alias/missing", recursive: false, optional: true) + #expect(!FileManager.default.fileExists(atPath: absent.path)) + #expect(throws: CoreError.self) { + _ = try view.resource("broken/missing", recursive: false, optional: true) + } + _ = try view.directory() + #expect(throws: CoreError.unsafePath("Git input is a link: ignored")) { + _ = try view.resource("ignored", recursive: false, followsLinks: false, optional: true) + } + let missing = try view.resource("real/missing", optional: true) + #expect(!FileManager.default.fileExists(atPath: missing.path)) + } + } + + @Test(arguments: [false, true]) + func excludedAncestorsDoNotHideBrokenLinks(_ warm: Bool) throws { + let fixture = try Repository() + try fixture.write("ignored export-ignore\n", ".gitattributes") + try fixture.write("present", "real") + let ignored = fixture.repo.appendingPathComponent("ignored") + try FileManager.default.createDirectory(at: ignored, withIntermediateDirectories: false) + for (link, target) in [("rule", "../real"), ("dangling", "../missing")] { + try FileManager.default.createSymbolicLink( + atPath: ignored.appendingPathComponent(link).path, withDestinationPath: target) + } + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + if warm { + _ = try view.directory() + #expect( + !FileManager.default.fileExists(atPath: view.root.appendingPathComponent("ignored").path)) + } + #expect(throws: CoreError.unsafePath("Git input is a link: ignored/rule")) { + _ = try view.resource("ignored/rule", recursive: false, followsLinks: false, optional: true) + } + #expect(throws: CoreError.self) { + _ = try view.resource("ignored/dangling", recursive: false, optional: true) + } + } + } + + @Test func cachedLookupTestsExactSpellingBeforeSymlinkPolicy() throws { + let fixture = try Repository() + try fixture.write("file", "original") + try FileManager.default.createSymbolicLink( + atPath: fixture.repo.appendingPathComponent("Link").path, withDestinationPath: "original") + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + for followsLinks in [false, true] { + let absent = try view.resource( + "link", recursive: false, followsLinks: followsLinks, optional: true) + #expect(!FileManager.default.fileExists(atPath: absent.path)) + } + _ = try view.directory() + let exact = try view.resource("Link") + #expect(try Data(contentsOf: exact) == Data("file".utf8)) + for miss in ["link", "LINK"] { + let aliasesExact = FileManager.default.fileExists( + atPath: view.root.appendingPathComponent(miss).path) + for followsLinks in [false, true] { + if aliasesExact { + #expect( + throws: CoreError.unsafePath( + "Git input spelling collides with a snapshot entry: " + miss) + ) { + _ = try view.resource( + miss, recursive: false, followsLinks: followsLinks, optional: true) + } + } else { + let absent = try view.resource( + miss, recursive: false, followsLinks: followsLinks, optional: true) + #expect(!FileManager.default.fileExists(atPath: absent.path)) + } + } + } + #expect(throws: CoreError.unsafePath("Git input is a link: Link")) { + _ = try view.resource("Link", recursive: false, followsLinks: false, optional: true) + } + } + } + + @Test(arguments: [false, true]) + func structuralDirectoriesAndGitlinksKeepTheirCommittedKinds(_ warm: Bool) throws { + let fixture = try Repository() + try fixture.write("docs export-ignore\n", ".gitattributes") + try fixture.write("hidden", "docs/file") + try fixture.commit() + let linkedCommit = try fixture.git(["rev-parse", "HEAD"]) + try fixture.git(["update-index", "--add", "--cacheinfo", "160000,\(linkedCommit),submodule"]) + try fixture.git(["commit", "-m", "add gitlink"]) + let revision = try fixture.git(["rev-parse", "HEAD"]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + if warm { + let root = try view.directory() + #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("docs").path)) + #expect( + try FileManager.default.contentsOfDirectory( + atPath: root.appendingPathComponent("submodule").path + ).isEmpty) + } + let docs = try view.resource("docs", recursive: false, optional: true) + #expect(try FileManager.default.contentsOfDirectory(atPath: docs.path).isEmpty) + #expect( + throws: CoreError.invalidState( + "Git commit \(revision) at submodule: path traverses a non-directory" + ) + ) { + _ = try view.resource("submodule/missing", recursive: false, optional: true) + } + } + } + + @Test func disposableBareMatchesGitInitAttributeBehavior() throws { + let fixture = try Repository() + try fixture.write("README export-subst\n", ".gitattributes") + try fixture.write("$Format:%H$\n", "readme") + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + let baseline = fixture.root.appendingPathComponent("baseline") + try fixture.git([ + "-c", "gc.auto=0", "-c", "maintenance.auto=false", "init", "--bare", "--template=", + "--initial-branch=unborn", baseline.path, + ]) + let objects = try GitObjectDirectory(repository: fixture.repo) + try Data((objects.objects.path + "\n").utf8).write( + to: baseline.appendingPathComponent("objects/info/alternates")) + let tar = fixture.root.appendingPathComponent("baseline.tar") + let expected = fixture.root.appendingPathComponent("expected") + try FileManager.default.createDirectory(at: expected, withIntermediateDirectories: false) + try fixture.git(["-C", baseline.path, "archive", "--output=" + tar.path, revision]) + try ProcessRunner.unpackGitArchive(tar, into: expected) + let bytes = try Data(contentsOf: expected.appendingPathComponent("readme")) + + let flushes = Mutex(0) + let generated = try DirectoryHandle.$synchronizationObserver.withValue( + .init(didSynchronize: { flushes.withLock { $0 += 1 } }) + ) { + try objects.borrow(in: fixture.root, named: "generated") + } + #expect(flushes.withLock { $0 } == 0) + for setting in ["core.ignorecase", "core.precomposeunicode"] { + let args = ["config", "--get", setting] + #expect( + try ProcessRunner.isolatedGit(args, in: baseline).stdout + == ProcessRunner.isolatedGit(args, in: generated).stdout) + } + let cache = SourceCache(store: fixture.store) + for historical in [false, true] { + try cache.withGitSelection( + fixture.source, revision: revision, selections: [.init(path: "readme")], + offline: true, historical: historical + ) { tree in + let actual = try Data(contentsOf: tree.appendingPathComponent("readme")) + #expect(actual == bytes) + } + } + } + + @Test(arguments: [false, true]) + func narrowArchiveReadsBesideAnUnavailableTree(_ recursive: Bool) throws { + let fixture = try Repository() + try fixture.write("$Format:%H %T$\n", "selected/manifest") + try fixture.write("retained sibling within the selected tree", "selected/other") + try fixture.write("manifest export-subst\nother export-ignore\n", "selected/.gitattributes") + try fixture.write("unavailable", "unrelated/child") + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + let tree = try fixture.git(["rev-parse", "HEAD^{tree}"]) + let missing = try fixture.git(["rev-parse", "HEAD:unrelated"]) + let objects = try GitObjectDirectory(repository: fixture.repo) + try FileManager.default.removeItem( + at: objects.objects.appendingPathComponent(String(missing.prefix(2))) + .appendingPathComponent(String(missing.dropFirst(2)))) + #expect(throws: CoreError.self) { try fixture.git(["ls-tree", "-r", revision]) } + let path = recursive ? "selected" : "selected/manifest" + try SourceCache(store: fixture.store).withGitSelection( + fixture.source, revision: revision, selections: [.init(path: path, recursive: recursive)], + offline: true + ) { archive in + let bytes = try String( + contentsOf: archive.appendingPathComponent("selected/manifest"), encoding: .utf8) + #expect(bytes == "\(revision) \(tree)\n") + #expect( + !FileManager.default.fileExists( + atPath: archive.appendingPathComponent("selected/other").path)) + #expect( + !FileManager.default.fileExists(atPath: archive.appendingPathComponent("unrelated").path)) + } + } + + @Test(arguments: [false, true]) + func ordinaryRootSelectionIncludesEmptyCommits(_ empty: Bool) throws { + let fixture = try Repository() + if !empty { try fixture.write("contents", "file") } + try fixture.git(["add", "."]) + try fixture.git(["commit", "--allow-empty", "-m", "fixture"]) + let revision = try fixture.git(["rev-parse", "HEAD"]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + let root = try view.directory() + #expect( + try FileManager.default.contentsOfDirectory(atPath: root.path) == (empty ? [] : ["file"])) + } + } + + @Test(arguments: [false, true]) + func advertisedTagObjectNeedsCommitTypeEvidence(_ tagFirst: Bool) throws { + let fixture = try Repository() + try fixture.write("contents", "file") + try fixture.commit() + try fixture.git(["-c", "tag.gpgsign=false", "tag", "-a", "release", "-m", "release"]) + let commit = try fixture.git(["rev-parse", "HEAD"]) + let tag = try fixture.git(["rev-parse", "release"]) + let custom = "refs/custom/release" + try fixture.git(["update-ref", custom, tag]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + for requirement in tagFirst ? [tag, custom] : [custom, tag] { + if requirement == tag { + let pins = try session.candidates(for: fixture.source, requirements: [.revision(tag)]) + #expect(pins.map(\.revision) == [commit]) + } else { + #expect(throws: CoreError.self) { + _ = try session.candidates(for: fixture.source, requirements: [.revision(custom)]) + } + } + } + } + } + + @Test func packedBranchCanBackASymlinkHEAD() throws { + let fixture = try Repository() + try fixture.write("contents", "file") + try fixture.commit() + let bare = fixture.root.appendingPathComponent("bare") + try fixture.git([ + "clone", "--bare", "--config", "maintenance.auto=false", "--config", "gc.auto=0", + "--", fixture.repo.path, bare.path, + ]) + try fixture.git(["-C", bare.path, "pack-refs", "--all", "--prune"]) + let head = bare.appendingPathComponent("HEAD") + try FileManager.default.removeItem(at: head) + try FileManager.default.createSymbolicLink( + atPath: head.path, withDestinationPath: "refs/heads/main") + #expect(!FileManager.default.fileExists(atPath: head.path)) + #expect(try SourceCache.isLocalRepository(bare)) + } + + @Test func newlineBearingObjectDirectorySurvivesBorrowing() throws { + let fixture = try Repository(name: "producer\n") + try fixture.write("contents", "file") + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + try SourceCache(store: fixture.store).withGitSelection( + fixture.source, revision: revision, selections: [.init(path: "file")], offline: true + ) { archive in + let bytes = try Data(contentsOf: archive.appendingPathComponent("file")) + #expect(bytes == Data("contents".utf8)) + } + } + + @Test(arguments: [false, true]) + func tarSelectionConsumesPAXSizeAcrossReadBoundaries(_ global: Bool) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + func header(_ name: String, size: Int, type: UInt8 = 48) -> Data { + var bytes = Data(count: 512) + bytes.replaceSubrange(0.. Data { + data + Data(count: (512 - data.count % 512) % 512) + } + let count = 3 * 65_536 + 3 + let first = Data("15 size=\(count)\n".utf8) + let next = Data("9 size=3\n".utf8) + let firstPAX = + header("PaxHeaders/skip", size: first.count, type: global ? 103 : 120) + pad(first) + let selectedPAX = header("PaxHeaders/keep", size: next.count, type: 120) + pad(next) + let selected = selectedPAX + header("keep", size: 0) + pad(Data("yes".utf8)) + let end = Data(count: 1024) + let tar = root.appendingPathComponent("input.tar") + let output = root.appendingPathComponent("output.tar") + let omitted = firstPAX + header("skip", size: 0) + pad(Data(repeating: 42, count: count)) + try (omitted + selected + end).write(to: tar) + let stream = try FileHandle(forReadingFrom: tar) + defer { try? stream.close() } + let kept = try GitTarSelection.copy(from: stream, to: output, keeping: [Data("keep".utf8)]) + #expect(kept == [Data("keep".utf8)]) + #expect(try Data(contentsOf: output) == (global ? firstPAX : Data()) + selected + end) + } + + @Test func localAdvertisementOmitsHiddenTagsAndRefExpressions() throws { + let fixture = try Repository() + try fixture.write("first", "value") + try fixture.commit() + try fixture.git(["tag", "-a", "1.1.0", "-m", "public"]) + let publicCommit = try fixture.git(["rev-parse", "HEAD"]) + try fixture.write("private", "value") + try fixture.commit() + let privateCommit = try fixture.git(["rev-parse", "HEAD"]) + try fixture.git(["tag", "1.9.0"]) + try fixture.git(["update-ref", "refs/heads/private", "HEAD"]) + try fixture.git(["reset", "--hard", publicCommit]) + try fixture.git(["update-ref", "refs/remotes/origin/main", publicCommit]) + try fixture.git(["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]) + let bare = fixture.root.appendingPathComponent("bare") + try fixture.git([ + "clone", "--mirror", "--no-local", "--config", "maintenance.auto=false", "--config", + "gc.auto=0", "--", fixture.repo.path, bare.path, + ]) + try fixture.git(["config", "--add", "uploadpack.hideRefs", "refs/heads/private"]) + try fixture.git(["config", "--add", "uploadpack.hideRefs", "refs/tags/1.9.0"]) + try fixture.git(["-C", bare.path, "config", "--add", "uploadpack.hideRefs", "refs/tags/1.9.0"]) + var constrained = fixture.source + constrained.requirement = .upToNextMajor(from: "1.0.0") + #expect( + try SourceCache(store: fixture.store).inspectRevision(constrained) + == SourceRevision(revision: publicCommit, version: "1.1.0")) + constrained.location = bare.path + #expect( + try SourceCache(store: fixture.store).inspectRevision(constrained) + == SourceRevision(revision: publicCommit, version: "1.1.0")) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let pins = try session.candidates( + for: fixture.source, requirements: [.upToNextMajor(from: "1.0.0")]) + #expect(pins.map(\.revision) == [publicCommit]) + #expect(pins.map(\.version) == ["1.1.0"]) + let peeled = try session.candidates( + for: fixture.source, requirements: [.revision("1.1.0^{commit}")]) + #expect(peeled.map(\.revision) == [publicCommit]) + let remoteHead = try session.candidates( + for: fixture.source, requirements: [.revision("refs/remotes/origin/HEAD^{commit}")]) + #expect(remoteHead.map(\.revision) == [publicCommit]) + let hidden = try session.candidates( + for: fixture.source, requirements: [.revision("private^{commit}")]) + #expect(hidden.isEmpty) + #expect(throws: CoreError.self) { + _ = try session.candidates(for: fixture.source, requirements: [.revision(privateCommit)]) + } + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + } + + @Test func sha256PinsUseTheProducerObjectFormat() throws { + let fixture = try Repository(format: "sha256") + try fixture.write("sha256", "file") + try fixture.commit() + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let pin = try #require(try session.candidates(for: fixture.source, requirements: [nil]).first) + #expect(pin.revision.count == 64) + let view = try session.snapshot(fixture.source, at: pin) + #expect(try String(contentsOf: view.resource("file"), encoding: .utf8) == "sha256") + } + } + + @Test func packedTagsRetainCaseDistinctNames() throws { + let fixture = try Repository() + try fixture.write("first", "value") + try fixture.commit() + let first = try fixture.git(["rev-parse", "HEAD"]) + try fixture.write("second", "value") + try fixture.commit() + let second = try fixture.git(["rev-parse", "HEAD"]) + try fixture.write( + "# pack-refs with: sorted\n\(second) refs/tags/1.2.0\n" + + "\(first) refs/tags/Release\n\(second) refs/tags/release\n", + ".git/packed-refs") + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let visible = try session.candidates( + for: fixture.source, requirements: [.upToNextMajor(from: "1.0.0")]) + #expect(visible == [.init(revision: second, version: "1.2.0")]) + for (tag, revision) in [("Release", first), ("release", second)] { + let selection = try session.candidates( + for: fixture.source, requirements: [.revision(tag + "^{commit}")]) + #expect(selection.map(\.revision) == [revision]) + } + } + } + + @Test func fallbackExpressionIgnoresInheritedURLRewrite() throws { + let fixture = try Repository() + try fixture.write("original", "value") + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + let redirected = fixture.root.appendingPathComponent("unadmitted").path + let child = try stateTestProcess( + root: fixture.root, + arguments: ["inspect-local-expression", String(revision.prefix(12))], + environment: [ + "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "url.\(redirected).insteadOf", + "GIT_CONFIG_VALUE_0": fixture.repo.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: fixture.root) + #expect(child.terminationStatus == 0) + #expect( + try String( + contentsOf: fixture.root.appendingPathComponent("selected-revision"), encoding: .utf8) + == revision) + } + + @Test func retentionSyncsTwoRevisionsUnderOneObjectBarrier() throws { + let fixture = try Repository() + try fixture.write("first", "file") + try fixture.commit() + let first = try fixture.git(["rev-parse", "HEAD"]) + try fixture.write("second", "file") + try fixture.commit() + let second = try fixture.git(["rev-parse", "HEAD"]) + var ledger = ResolvedLedger() + for revision in [first, second] { + ledger.sources[revision] = .init( + kind: .local, location: .init(kind: .absolute, path: fixture.repo.path), revision: revision) + } + let references = try RetentionReferences(ledger: ledger, roots: [:]) + var events: [String] = [] + let cache = SourceCache(store: fixture.store, checkpoint: { events.append($0) }) + try cache.retain(references: references) + #expect(events.filter { $0.hasSuffix(".watch.objects.synced") }.count == 1) + #expect(events.filter { $0.hasSuffix(".updated") }.count == 2) + let identity = try fixture.source.identity(environment: fixture.store.environment) + let mirror = cache.mirrorURL(sourceID: identity) + for revision in [first, second] { + let ref = "refs/agents-watch/" + revision + let retained = try ProcessRunner.isolatedGit(["rev-parse", "--verify", ref], in: mirror) + #expect(retained.stdout.trimmingCharacters(in: .newlines) == revision) + } + } + + @Test(arguments: ["missing", "escape", "cycle"]) + func requiredLinksReportFailure(_ kind: String) throws { + let fixture = try Repository() + try fixture.write("fixture", "file") + let link = fixture.repo.appendingPathComponent("alias") + let target = + switch kind { + case "escape": "../outside" + case "cycle": "alias" + default: "missing" + } + try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: target) + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(fixture.source, at: .init(revision: revision)) + let absent = try view.resource("absent", recursive: true, optional: true) + #expect(!FileManager.default.fileExists(atPath: absent.path)) + #expect(throws: CoreError.self) { try view.resource("alias/file") } + } + } + + @Test func authoringCoordinatesPreserveFilesystemOrder() throws { + let root = URL(fileURLWithPath: "/workspace", isDirectory: true) + let relative = LedgerLocation( + kind: .authoringRelative, root: "project", path: "base/./alias/../edit") + #expect(try relative.authoredPath(roots: ["project": root]) == "/workspace/base/alias/../edit") + #expect(relative.appendingAuthoredPath(".") == relative) + let absolute = LedgerLocation(kind: .absolute, path: "/workspace//base/.") + #expect(try absolute.authoredPath(roots: [:]) == "/workspace/base") + #expect(absolute.appendingAuthoredPath("nested").path == "/workspace/base/nested") + } +} + +private final class Repository { + let root: URL + let repo: URL + let store: StateStore + var source: SourceDeclaration { .init(kind: .local, location: repo.path) } + + init(format: String = "sha1", name: String = "producer") throws { + root = try temporaryDirectory() + repo = root.appendingPathComponent(name) + store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + do { + try FileManager.default.createDirectory(at: repo, withIntermediateDirectories: false) + try git(["init", "--initial-branch=main", "--object-format=" + format]) + try git(["config", "user.name", "Fixture"]) + try git(["config", "user.email", "fixture@example.invalid"]) + try git(["config", "maintenance.auto", "false"]) + try git(["config", "gc.auto", "0"]) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { removeTemporaryDirectory(root) } + + func write(_ text: String, _ path: String) throws { + let file = repo.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } + + func commit() throws { + try git(["add", "."]) + try git(["commit", "-m", "fixture"]) + } + + @discardableResult + func git(_ args: [String]) throws -> String { + try ProcessRunner.run( + "/usr/bin/env", arguments: ["git", "-C", repo.path, "-c", "commit.gpgsign=false"] + args + ).stdout.trimmingCharacters(in: .newlines) + } +} diff --git a/Tests/AgentsCoreTests/SourceCacheTests.swift b/Tests/AgentsCoreTests/SourceCacheTests.swift index 9617be4..ff86d16 100644 --- a/Tests/AgentsCoreTests/SourceCacheTests.swift +++ b/Tests/AgentsCoreTests/SourceCacheTests.swift @@ -7,7 +7,7 @@ import Testing @Suite("Source cache") struct SourceCacheTests { - @Test func sharesExactTreesAndPrunesOnlyUnreferencedPins() throws { + @Test func exactSnapshotsDoNotPublishPins() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } let repo = root.appendingPathComponent("upstream") @@ -22,15 +22,16 @@ struct SourceCacheTests { let id = try source.identity(environment: environment) let locked = LockedSource(kind: .local) let first = try cache.resolve(source) - let tree = try cache.materialize(sourceID: id, source: locked, revision: first.revision) - #expect(try cache.materialize(sourceID: id, source: locked, revision: first.revision) == tree) - #expect(!FileManager.default.fileExists(atPath: tree.appendingPathComponent(".git").path)) + try cache.withSnapshot(sourceID: id, source: locked, revision: first.revision) { tree throws in + #expect(!FileManager.default.fileExists(atPath: tree.appendingPathComponent(".git").path)) + #expect( + try String(contentsOf: tree.appendingPathComponent("content"), encoding: .utf8) == "A") + } try Data("B".utf8).write(to: repo.appendingPathComponent("content")) try ProcessRunner.run( "/usr/bin/env", arguments: ["git", "-C", repo.path, "commit", "-am", "B"]) let second = try cache.resolve(source) #expect(first != second) - #expect(try String(contentsOf: tree.appendingPathComponent("content"), encoding: .utf8) == "A") try cache.withSnapshot(sourceID: id, source: locked, revision: second.revision) { snapshot throws in #expect( @@ -39,13 +40,7 @@ struct SourceCacheTests { #expect( !FileManager.default.fileExists( atPath: cache.materializedURL(sourceID: id, revision: second.revision).path)) - var references = RetentionReferences() - references.git.insert(.init(source: id, revision: first.revision)) - references.sourceLocations[id] = repo.path - try prune(cache, references: references) - #expect(FileManager.default.fileExists(atPath: tree.path)) - try prune(cache, references: RetentionReferences()) - #expect(!FileManager.default.fileExists(atPath: tree.path)) + } @Test(arguments: [ @@ -71,18 +66,20 @@ struct SourceCacheTests { let cache = SourceCache(store: StateStore(scope: .project, environment: environment)) let source = SourceDeclaration(kind: .local, location: repo.path) let pin = try cache.resolve(source) - let materialize = { - try cache.materialize( - sourceID: source.identity(environment: environment), source: LockedSource(kind: .local), - revision: pin.revision) - } + let id = try source.identity(environment: environment) if kept { - let tree = try materialize() - #expect( - try FileManager.default.destinationOfSymbolicLink( - atPath: tree.appendingPathComponent("docs/link").path) == destination) + try cache.withSnapshot(sourceID: id, source: .init(kind: .local), revision: pin.revision) { + tree throws in + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: tree.appendingPathComponent("docs/link").path) == destination) + } } else { - #expect(throws: CoreError.self) { try materialize() } + #expect(throws: CoreError.self) { + try cache.withSnapshot(sourceID: id, source: .init(kind: .local), revision: pin.revision) { + _ in + } + } } } @@ -107,12 +104,14 @@ struct SourceCacheTests { let source = SourceDeclaration(kind: .local, location: repo.path, requirement: requirement) let pin = try cache.resolve(source) #expect(pin.version == expected) - let tree = try cache.materialize( - sourceID: source.identity(environment: environment), source: LockedSource(kind: .local), - revision: pin.revision) - #expect( - try String(contentsOf: tree.appendingPathComponent("content"), encoding: .utf8) - == "committed") + try cache.withSnapshot( + sourceID: source.identity(environment: environment), source: .init(kind: .local), + revision: pin.revision + ) { tree throws in + #expect( + try String(contentsOf: tree.appendingPathComponent("content"), encoding: .utf8) + == "committed") + } } } @@ -168,10 +167,7 @@ extension SourceCacheTests { try FileManager.default.createDirectory( at: link.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.createSymbolicLink(at: link, withDestinationURL: external) - var references = RetentionReferences() - references.git.insert(.init(source: id, revision: revision)) - references.sourceLocations[id] = String(id.dropFirst(6)) - #expect(throws: CoreError.self) { try prune(cache, references: references) } + #expect(throws: CoreError.self) { try cache.existingMaterializedPins() } #expect( try String(contentsOf: external.appendingPathComponent("unrelated"), encoding: .utf8) == "keep") diff --git a/Tests/AgentsCoreTests/SourceRegressionTests.swift b/Tests/AgentsCoreTests/SourceRegressionTests.swift index bb40859..696cf65 100644 --- a/Tests/AgentsCoreTests/SourceRegressionTests.swift +++ b/Tests/AgentsCoreTests/SourceRegressionTests.swift @@ -163,16 +163,19 @@ struct SourceRegressionTests { let source = SourceDeclaration( kind: .local, location: repo.path, requirement: .branch("master")) let first = try cache.resolve(source) - let tree = try cache.materialize( - sourceID: source.identity(environment: environment), source: LockedSource(kind: .local), - revision: first.revision) try Data("B".utf8).write(to: repo.appendingPathComponent("content")) try ProcessRunner.run( "/usr/bin/env", arguments: ["git", "-C", repo.path, "commit", "-am", "B"]) let second = try cache.resolve(source) #expect(second.revision == (try gitHead(repo))) #expect(second.revision != first.revision) - #expect(try String(contentsOf: tree.appendingPathComponent("content"), encoding: .utf8) == "A") + try cache.withSnapshot( + sourceID: source.identity(environment: environment), source: .init(kind: .local), + revision: first.revision + ) { tree throws in + #expect( + try String(contentsOf: tree.appendingPathComponent("content"), encoding: .utf8) == "A") + } } @Test(arguments: [ @@ -199,11 +202,13 @@ struct SourceRegressionTests { kind: .local, location: root.appendingPathComponent("repo").path, requirement: requirement) let pin = try cache.resolve(source) #expect(pin.version == expected) - let tree = try cache.materialize( + try cache.withSnapshot( sourceID: source.identity(environment: cache.store.environment), - source: LockedSource(kind: .local), revision: pin.revision) - #expect( - try String(contentsOf: tree.appendingPathComponent("content"), encoding: .utf8) == expected) + source: .init(kind: .local), revision: pin.revision + ) { tree throws in + #expect( + try String(contentsOf: tree.appendingPathComponent("content"), encoding: .utf8) == expected) + } } @Test(arguments: ["1.0.0-alpha.1", "1.5.0-alpha.1", "2.0.0-alpha.1"]) diff --git a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift index 2135a26..2045252 100644 --- a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift +++ b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift @@ -64,16 +64,35 @@ struct WatchMirrorConcurrencyTests { #expect(!exists(fixture.store.cacheDirectory)) try FileManager.default.removeItem(at: listingResult) - let template = fixture.root.appendingPathComponent("template") - let pause = try GitTransactionPause( - root: fixture.root, hooks: template.appendingPathComponent("hooks"), - condition: "[ \"${ref#refs/heads/}\" != \"$ref\" ]") - defer { pause.terminate() } + let ready = try ProcessSignal(at: fixture.root.appendingPathComponent("archive-ready")) + let release = try ProcessSignal(at: fixture.root.appendingPathComponent("archive-release")) + let bin = fixture.root.appendingPathComponent("bin") + try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: false) + let git = bin.appendingPathComponent("git") + try Data( + """ + #!/bin/sh + /usr/bin/git "$@" || exit "$?" + root=${0%/bin/git} + for argument in "$@"; do + if [ "$argument" = archive ] && [ ! -e "$root/archive-paused" ]; then + touch "$root/archive-paused" + printf '%s\\n' ready > "$root/archive-ready" + read -r released < "$root/archive-release" + fi + done + """.utf8 + ).write(to: git) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: git.path) + let path = ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin" let listing = try stateTestProcess( root: fixture.root, arguments: ["instruction-list", ""], - environment: ["GIT_TEMPLATE_DIR": template.path]) - defer { terminateProcess(listing) } - try pause.wait() + environment: ["PATH": bin.path + ":" + path]) + defer { + try? release.send("release") + terminateProcess(listing) + } + #expect(try ready.receive() == "ready") #expect(listing.isRunning) #expect(!exists(listingResult)) #expect(!exists(fixture.store.directory)) @@ -90,7 +109,8 @@ struct WatchMirrorConcurrencyTests { #expect(try gitLocks(fixture).isEmpty) let published = try FileHash.folderHash(fixture.store.directory) - try finishProcesses([listing], root: fixture.root, resuming: pause) + try release.send("release") + try finishProcesses([listing], root: fixture.root) #expect(try String(contentsOf: listingResult, encoding: .utf8) == "rule") #expect(try FileHash.folderHash(fixture.store.directory) == published) #expect(try fixture.store.loadWatch().sources[fixture.id]?.seen == .revision(fixture.head())) diff --git a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift index ed0a9f2..fc73f06 100644 --- a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift +++ b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift @@ -1,11 +1,12 @@ import AgentsCore -import AgentsInstructions import AgentsManifest import AgentsUpdates import Foundation import StateTestSupport import Testing +@testable import AgentsInstructions + @Suite("Instruction source diagnostics") struct InstructionSourceDiagnosticTests { @Test(arguments: [SourceKind.local, .git]) @@ -197,6 +198,83 @@ struct InstructionSourceDiagnosticTests { #expect(try fixture.snapshot() == before) } + @Test func pathScopedAliasesInspectTheirOwnTransports() throws { + let fixture = try InstructionFixture() + try fixture.section("alpha", container: "alpha/instructions") + try fixture.section("beta", container: "beta/instructions") + try fixture.commit() + let store = fixture.store() + let original = "file://localhost" + fixture.repo.path + let alpha = SourceDeclaration( + kind: .git, location: original, requirement: .branch("main"), path: "alpha") + var beta = alpha + beta.path = "beta" + try store.save( + declaration: Declaration( + agents: [.codex], sources: ["first": alpha, "second": beta], + instructions: InstructionsDeclaration(sections: ["first:alpha", "second:beta"])), + ledger: ResolvedLedger()) + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + let ledger = try store.loadLedger() + #expect(Set(ledger.sourceUses.map(\.root)) == ["alpha", "beta"]) + + let alternate = URL(fileURLWithPath: fixture.repo.path + ".git") + try fixture.git([ + "clone", "--no-local", "--config", "maintenance.auto=false", "--config", "gc.auto=0", + "--", fixture.repo.path, alternate.path, + ]) + try fixture.git([ + "-C", alternate.path, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", + "-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "alternate revision", + ]) + let updated = try fixture.git(["-C", alternate.path, "rev-parse", "HEAD"]) + beta.location = "file://localhost" + alternate.path + #expect( + try beta.identity(environment: fixture.environment) + == alpha.identity(environment: fixture.environment)) + let authored = try String(contentsOf: store.declarationURL, encoding: .utf8) + let secondTransport = try #require(authored.range(of: original, options: .backwards)) + try Data(authored.replacingCharacters(in: secondTransport, with: beta.location).utf8) + .write(to: store.declarationURL) + let declaration = try store.loadDeclaration() + #expect(declaration.sources["first"]?.location == alpha.location) + #expect(declaration.sources["second"]?.location == beta.location) + let before = try fixture.snapshot() + let diagnostics = try InstructionOperations.doctor(environment: fixture.environment).diagnostics + let updates = diagnostics.filter { $0.kind == .sourceUpdateAvailable } + try #require(updates.count == 1, "\(diagnostics)") + let update = try #require(updates.first) + #expect(update.message.contains(" at beta:")) + #expect(update.message.contains(updated)) + #expect(update.message.contains("File sections: beta.")) + #expect(!diagnostics.contains { $0.kind == .sourceResolutionFailed }) + #expect(try fixture.snapshot() == before) + } + + @Test func revisionMemoKeepsUnicodeDistinctTransportsSeparate() throws { + let composed = SourceDeclaration( + kind: .git, location: "ssh://fixture.invalid/r\u{00e9}po.git", + requirement: .branch("main"), path: "alpha") + let decomposed = SourceDeclaration( + kind: .git, location: "ssh://fixture.invalid/re\u{0301}po.git", + requirement: .branch("main"), path: "beta") + #expect(composed.location == decomposed.location) + let firstURL = try #require(URL(string: composed.location)) + let secondURL = try #require(URL(string: decomposed.location)) + #expect(firstURL.absoluteString != secondURL.absoluteString) + let identity = try composed.transportIdentity() + #expect(try decomposed.transportIdentity() == identity) + let first = InstructionSourceDiagnostics.RevisionKey(identity: identity, source: composed) + let second = InstructionSourceDiagnostics.RevisionKey(identity: identity, source: decomposed) + let firstRevision = SourceRevision(revision: String(repeating: "a", count: 40)) + let secondRevision = SourceRevision(revision: String(repeating: "b", count: 40)) + var memo = [first: firstRevision] + #expect(memo[second] == nil) + memo[second] = secondRevision + #expect(memo[first] == firstRevision) + #expect(memo[second] == secondRevision) + } + private func install( _ fixture: InstructionFixture, kind: SourceKind, requirement: SourceRequirement, files: [String] = ["file"] diff --git a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift index c302839..7b10ea4 100644 --- a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift +++ b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift @@ -122,10 +122,11 @@ struct AutomaticSelectionTests { /usr/bin/git "$@" result=$? [ "$result" -eq 0 ] || exit "$result" + root=${0%/bin/git} for argument in "$@"; do - if [ "$argument" = archive ] && [ ! -e "$SELECTION_TEST_ROOT/discovery-ready" ]; then - touch "$SELECTION_TEST_ROOT/discovery-ready" - read -r resume < "$SELECTION_TEST_ROOT/resume-discovery" + if [ "$argument" = archive ] && [ ! -e "$root/discovery-ready" ]; then + touch "$root/discovery-ready" + read -r resume < "$root/resume-discovery" fi done """.utf8 @@ -142,7 +143,6 @@ struct AutomaticSelectionTests { child.arguments = [root.path, "automatic-add", kind] var environment = ProcessInfo.processInfo.environment environment["PATH"] = bin.path + ":" + (environment["PATH"] ?? "/usr/bin:/bin") - environment["SELECTION_TEST_ROOT"] = root.path child.environment = environment try child.run() return child diff --git a/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift b/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift index afbbf91..275d490 100644 --- a/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift +++ b/Tests/AgentsSkillsTests/CodexUserIsolationTests.swift @@ -63,8 +63,10 @@ struct CodexUserIsolationTests { } } - @Test(arguments: [false, true]) - func instructionOnlyRestoreOrUpdatePreservesLegacySkillOwnership(_ restore: Bool) throws { + @Test(arguments: [false, true], [false, true]) + func instructionOnlyRestoreOrUpdatePreservesLegacySkillOwnership( + _ restore: Bool, _ withLiveEdit: Bool + ) throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "managed") let instructions = fixture.repo.appendingPathComponent("instructions") @@ -77,6 +79,7 @@ struct CodexUserIsolationTests { InstructionAddOptions( source: fixture.repo.path, names: ["rules"], agents: [.codex], scope: .user, environment: fixture.environment)) + let edit = try withLiveEdit ? installLiveRootSkill(fixture) : nil let instructionTarget = fixture.environment.homeDirectory.appendingPathComponent( ".codex/AGENTS.md") try FileManager.default.removeItem(at: instructionTarget) @@ -93,14 +96,30 @@ struct CodexUserIsolationTests { } let ledger = try fixture.store(.user).loadLedger() #expect( - ledger.deployments.first { $0.route == "agents/skill@1" }?.target.root == "skills-codex") + ledger.deployments.first { $0.route == "agents/skill@1" && $0.target.path == "demo" }? + .target.root == "skills-codex") #expect(try String(contentsOf: instructionTarget, encoding: .utf8).contains("Restored rules")) #expect(try fixture.body(sharedSkill).contains("managed")) - try SkillOperations.remove( - skillNames: ["demo"], scope: .user, agents: [.codex], environment: fixture.environment) - #expect(try fixture.body(privateSkill) == "unmanaged private") - #expect(!FileManager.default.fileExists(atPath: sharedSkill.path)) + if let edit { + let live = try #require( + ledger.components.values.first { $0.kind == "skills" && $0.name == "live" }) + let resource = try #require(live.resources.first.flatMap { ledger.resources[$0] }) + #expect(resource.kind == .liveEdit && resource.path == ".") + #expect( + ledger.deployments.contains { + $0.route == "agents/skill@1" && $0.target.root == "skills-codex-private" + && $0.target.path == "live" + }) + try edit.target.validate() + #expect( + try Data(contentsOf: edit.target.url.appendingPathComponent("SKILL.md")) == edit.bytes) + } else { + try SkillOperations.remove( + skillNames: ["demo"], scope: .user, agents: [.codex], environment: fixture.environment) + #expect(try fixture.body(privateSkill) == "unmanaged private") + #expect(!FileManager.default.fileExists(atPath: sharedSkill.path)) + } } @Test func migrationKeepsCursorOwnedSharedLeafAndWarnsOnlyAboutUnmanagedLinks() throws { @@ -161,6 +180,23 @@ struct CodexUserIsolationTests { ).map(\.name) == ["demo"]) } + private func installLiveRootSkill(_ fixture: SkillFixture) throws + -> (target: TargetPrecondition, bytes: Data) + { + let liveRoot = fixture.root.appendingPathComponent("live-root") + try FileManager.default.createDirectory(at: liveRoot, withIntermediateDirectories: false) + let liveFile = liveRoot.appendingPathComponent("SKILL.md") + let original = Data("---\nname: live\ndescription: Live skill\n---\n\n# Live\n".utf8) + try original.write(to: liveFile) + _ = try SkillOperations.add( + AddOptions( + source: liveRoot.path, agents: [.codex], scope: .user, mode: .edit, all: true, + environment: fixture.environment)) + let edited = original + Data("\nEdited at the source\n".utf8) + try edited.write(to: liveFile) + return (try TargetPrecondition(fixture.target("live", scope: .user)), edited) + } + private func seedLegacy(_ fixture: SkillFixture) throws -> (URL, URL) { let privateSkill = fixture.target("demo", scope: .user) let sharedSkill = fixture.environment.homeDirectory.appendingPathComponent( @@ -175,7 +211,9 @@ struct CodexUserIsolationTests { let store = fixture.store(.user) var ledger = try store.loadLedger() let index = try #require( - ledger.deployments.firstIndex { $0.route == "agents/skill@1" && $0.recipients == [.codex] }) + ledger.deployments.firstIndex { + $0.route == "agents/skill@1" && $0.recipients == [.codex] && $0.target.path == "demo" + }) ledger.deployments[index].target.root = "skills-codex" try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) return (privateSkill, sharedSkill) diff --git a/Tests/AgentsSkillsTests/InstallationSafetyTests.swift b/Tests/AgentsSkillsTests/InstallationSafetyTests.swift index cdc33e7..7b03e15 100644 --- a/Tests/AgentsSkillsTests/InstallationSafetyTests.swift +++ b/Tests/AgentsSkillsTests/InstallationSafetyTests.swift @@ -66,9 +66,12 @@ struct InstallationSafetyTests { let cache = SourceCache(store: fixture.store()) let one = try #require(fixture.store().loadResolved().skills["one"]) let tree = cache.materializedURL(sourceID: one.source, revision: try #require(one.revision)) + let legacySkill = tree.appendingPathComponent("skills/two") + try FileManager.default.copyItem( + at: fixture.repo.appendingPathComponent("skills/two"), to: legacySkill) _ = try SkillOperations.add( AddOptions( - source: tree.appendingPathComponent("skills/two").path, alias: "live", agents: [.codex], + source: legacySkill.path, alias: "live", agents: [.codex], mode: .edit, environment: fixture.environment)) _ = try SkillOperations.remove(skillNames: ["one"], environment: fixture.environment) #expect(try fixture.body(fixture.target("two")).contains("B")) diff --git a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift index c56570c..e872fc8 100644 --- a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift @@ -189,8 +189,7 @@ struct RetainedLifecycleTests { #expect(!FileManager.default.fileExists(atPath: shared.path)) #expect(!FileManager.default.fileExists(atPath: antigravity.path)) #expect(try fixture.store(.user).loadResolved().skills.isEmpty) - let materialized = fixture.store(.user).cacheDirectory.appendingPathComponent("materialized") - #expect(try FileManager.default.contentsOfDirectory(atPath: materialized.path).isEmpty) + #expect(try SourceCache(store: fixture.store(.user)).existingMaterializedPins().isEmpty) } @Test func rejectsRemoteEditAndRestoresDeletedLiveInstallation() throws { diff --git a/Tests/AgentsUpdatesTests/AntigravityInstructionTests.swift b/Tests/AgentsUpdatesTests/AntigravityInstructionTests.swift index 284a1e4..c111462 100644 --- a/Tests/AgentsUpdatesTests/AntigravityInstructionTests.swift +++ b/Tests/AgentsUpdatesTests/AntigravityInstructionTests.swift @@ -69,7 +69,11 @@ struct AntigravityInstructionTests { #expect(deployment.expectedHash == "sha256:" + FileHash.sha256Hex(data: output)) #expect(owner.revision == (try f.git(["rev-parse", "HEAD"]))) #expect(owner.resources.count == 3) - #expect(owner.resources.allSatisfy { lock.resources[$0]?.kind == .embedded }) + #expect( + owner.resources.allSatisfy { id in + lock.resources[id]?.kind == .git + && lock.resources[id]?.entries.allSatisfy { $0.object == nil } == true + }) try f.write("new upstream bytes", to: body) try f.commit() @@ -378,3 +382,441 @@ struct AntigravityInstructionTests { } } } + +extension AntigravityInstructionTests { + @Test func doctorSeparatesNestedIncludeTamperingFromRuleDrift() throws { + let f = try UpdateFixture(scope: .user) + try f.write( + "---\ndescription: A rule.\n---\n\n# Rules\n\n@[first](../includes/first.md)\n", + to: f.repo.appendingPathComponent("instructions/rules.md")) + try f.write( + "Nested @[body](body.txt)\n", to: f.repo.appendingPathComponent("includes/first.md")) + try f.write("retained", to: f.repo.appendingPathComponent("includes/body.txt")) + try f.commit() + try declare(f, name: "rules") + _ = try f.apply() + let revision = try f.git(["rev-parse", "HEAD"]) + let identity = try SourceDeclaration(kind: .local, location: f.repo.path).identity( + environment: f.environment) + let tree = SourceCache(store: f.store).materializedURL(sourceID: identity, revision: revision) + try f.write("tampered", to: tree.appendingPathComponent("includes/body.txt")) + try f.write("producer edit", to: f.repo.appendingPathComponent("includes/body.txt")) + let ledger = try f.store.loadLedger() + let rule = try #require(ledger.deployments.first { $0.recipients == [.antigravity] }) + let destination = try rule.target.resolve(roots: f.store.ledgerRoots) + try (f.bytes(destination) + Data("drift".utf8)).write(to: destination) + let diagnostics = try doctor(f).diagnostics + #expect( + diagnostics.filter { + $0.kind == .stateUnavailable && $0.message.contains("includes/body.txt") + }.count == 1) + #expect( + diagnostics.contains { + $0.kind == .uncommittedSource && $0.message.contains("includes/body.txt") + }) + #expect(diagnostics.contains { $0.kind == .drift && $0.path == destination }) + } + + @Test(arguments: [false, true]) + func legacyRulePreservesFilteredLockAndCanRestoreWithoutGit(_ offline: Bool) throws { + let f = try UpdateFixture(scope: .user) + if offline { + try f.write( + "---\ndescription: Fixture.\n---\n\n# Rule\n\n@[body](../include/body.txt)\n", + to: f.repo.appendingPathComponent("instructions/rules.md")) + try f.write("pinned include", to: f.repo.appendingPathComponent("include/body.txt")) + try f.commit() + } + try declare(f, name: "rules", agents: offline ? [.antigravity] : [.antigravity, .codex]) + _ = try f.apply() + let source = try f.store.loadDeclaration() + let git = try f.store.loadLedger() + let legacy = try embeddedRuleLock(git, repository: f.repo) + try f.store.save(declaration: source, ledger: legacy) + let original = try f.bytes(f.store.resolvedURL) + let fileNumber = + try FileManager.default.attributesOfItem(atPath: f.store.resolvedURL.path)[.systemFileNumber] + as? NSNumber + for kind in [DeclaredComponentKind.skills, .instructions] { + let request = UpdateRequest(kinds: [kind]) + let preview = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + #expect(!preview.hasChanges) + try apply(f, request: request, preview: preview) + #expect(try f.bytes(f.store.resolvedURL) == original) + #expect( + try FileManager.default.attributesOfItem(atPath: f.store.resolvedURL.path)[ + .systemFileNumber] as? NSNumber == fileNumber) + } + let retained = try RetentionReferences(ledger: legacy, roots: f.store.ledgerRoots) + #expect(retained.requiredGitObjects.isEmpty) + #expect(retained.protectedGitRefs.count == 1) + let rule = try #require(git.deployments.first { $0.recipients == [.antigravity] }) + let destination = try rule.target.resolve(roots: f.store.ledgerRoots) + let expected = try f.bytes(destination) + for directory in [f.repo, f.store.cacheDirectory] { + try FileManager.default.removeItem(at: directory) + } + try FileManager.default.removeItem(at: destination) + if offline { + _ = try UpdateOperations.restore(scope: .user, environment: f.environment, offline: true) + } else { + _ = try InstructionOperations.installResolvedReport(scope: .user, environment: f.environment) + } + #expect(try f.bytes(destination) == expected) + #expect(try f.bytes(f.store.resolvedURL) == original) + #expect( + !FileManager.default.fileExists( + atPath: f.store.cacheDirectory.appendingPathComponent("mirrors").path)) + } + + @Test func filteredPrivateHookRecreationPreservesLegacyRuleAndRefreshesAuthority() throws { + struct Bindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data("filtered-private-hook-canary".utf8) + } + } + + let f = try UpdateFixture(scope: .user) + try declare(f, name: "rules") + var declaration = try f.store.loadDeclaration() + declaration.components.append( + .hook( + name: "check", event: .native("SessionStart"), + run: .init(executable: "never-run", environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode])) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + func update(_ request: UpdateRequest = UpdateRequest()) throws { + _ = try UpdateOperations.withPreparedUpdate( + request, scope: .user, environment: f.environment, bindingProvider: Bindings() + ) { try $0.apply() } + } + + try update() + let legacy = try embeddedRuleLock(f.store.loadLedger(), repository: f.repo) + let rule = try #require(legacy.deployments.first { $0.recipients == [.antigravity] }) + let ruleURL = try rule.target.resolve(roots: f.store.ledgerRoots) + let ruleBytes = try f.bytes(ruleURL) + try f.store.save(declaration: declaration, ledger: legacy) + let settings = try f.store.withLock(footprint: [.claudeSettingsUser]) { + try f.store.nativeTarget(for: .claudeSettingsUser).url + } + try FileManager.default.removeItem(at: settings) + + let hookOnly = UpdateRequest(kinds: [.hook]) + try update(hookOnly) + let current = try UpdateOperations.inspect(scope: .user, environment: f.environment) + let hook = try #require(current.components.first { $0.kind == .hook }) + let deployment = try #require( + current.deployments.first { $0.ownerRecords.contains(hook.record) }) + #expect(deployment.status == .current) + #expect(deployment.privateMaterialization) + #expect( + try String(contentsOf: settings, encoding: .utf8).contains("filtered-private-hook-canary")) + let recreated = try f.store.loadLedger() + #expect(recreated.resources == legacy.resources) + #expect(recreated.deployments.contains(rule)) + #expect(try f.bytes(ruleURL) == ruleBytes) + #expect(recreated.nativeAuthorities != legacy.nativeAuthorities) + + let lockBytes = try f.bytes(f.store.resolvedURL) + func lockInode() throws -> NSNumber? { + try FileManager.default.attributesOfItem(atPath: f.store.resolvedURL.path)[.systemFileNumber] + as? NSNumber + } + let inode = try #require(try lockInode()) + try update(hookOnly) + #expect(try f.bytes(f.store.resolvedURL) == lockBytes) + #expect(try lockInode() == inode) + + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [hook.selection]), scope: .user, + environment: f.environment + ) { try $0.apply() } + let remaining = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(!remaining.components.contains { $0.kind == .hook }) + #expect(try f.store.loadLedger().nativeAuthorities == nil) + let document = try #require( + JSONSerialization.jsonObject(with: f.bytes(settings)) as? [String: Any]) + #expect(document["hooks"] == nil) + #expect(try f.bytes(ruleURL) == ruleBytes) + } + + @Test(arguments: [false, true]) + func filteredMigrationChecksTheProtectedContributionToSharedOutput(_ alterRule: Bool) throws { + let f = try UpdateFixture(scope: .user) + try f.write( + "---\ndescription: Include fixture.\n---\n# Included rule\n\n@[body](../include/body.txt)\n", + to: f.repo.appendingPathComponent("instructions/with-include.md")) + try f.write("locked included body", to: f.repo.appendingPathComponent("include/body.txt")) + try f.commit() + let revision = try f.git(["rev-parse", "HEAD"]) + let identity = try SourceDeclaration(kind: .local, location: f.repo.path).identity( + environment: f.environment) + let pin = SourceCache(store: f.store).materializedURL(sourceID: identity, revision: revision) + let team = f.root.appendingPathComponent("team") + func writeTeam(_ text: String) throws { + try f.write( + "---\ndescription: Team instructions.\n---\n# Team\n\n\(text)\n", + to: team.appendingPathComponent("instructions/guide.md")) + } + try writeTeam("Original team") + let declaration = Declaration( + sources: [ + "fixture": .init(kind: .local, location: f.repo.path), + "team": .init(kind: .local, location: team.path), + ], + components: [ + .instructions(.init(agents: [.antigravity, .codex], sections: ["fixture:rules"])), + .instructions(.init(agents: [.codex], sections: ["team:guide"])), + .instructions(.init(agents: [.antigravity], sections: ["fixture:with-include"])), + ]) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let pinned = try f.store.loadLedger() + let rules = try pinned.deployments.filter { $0.recipients == [.antigravity] }.map { + let url = try $0.target.resolve(roots: f.store.ledgerRoots) + return (url, try f.bytes(url)) + } + #expect(rules.count == 2) + #expect( + rules.contains { String(decoding: $0.1, as: UTF8.self).contains("locked included body") }) + let legacy = try embeddedRuleLock(pinned, repository: f.repo) + try f.store.save(declaration: declaration, ledger: legacy) + try FileManager.default.removeItem(at: pin) + try writeTeam("Edited team") + let request: UpdateRequest + if alterRule { + var edited = declaration + edited.components[0] = .instructions( + .init(agents: [.antigravity], sections: ["fixture:rules"])) + request = .init(operation: .declaration(edited), kinds: [.instructions], names: ["guide"]) + do { + _ = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + Issue.record("Accepted a changed protected Antigravity contribution") + } catch let error as CoreError { + #expect(error.description.contains("requiresCombinedUpdate")) + } + } else { + request = .init(kinds: [.instructions], names: ["guide"]) + let preview = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + #expect(preview.hasChanges) + try apply(f, request: request, preview: preview) + let output = String(decoding: try f.bytes(f.instruction(.codex)), as: UTF8.self) + #expect(output.contains("Edited team") && output.contains("old")) + let migrated = try f.store.loadLedger() + let protectedInput = try #require( + migrated.resources.values.first { + $0.path == "instructions/rules.md" + }) + #expect(protectedInput.kind == .git) + #expect( + FileManager.default.fileExists(atPath: pin.appendingPathComponent(protectedInput.path).path) + ) + #expect( + try f.bytes(pin.appendingPathComponent("include/body.txt")) + == Data("locked included body".utf8)) + #expect( + !((try doctor(f)).diagnostics.contains { $0.kind == .stateUnavailable || $0.kind == .drift }) + ) + } + for (url, bytes) in rules { #expect(try f.bytes(url) == bytes) } + } + + @Test func filteredMigrationPreservesProtectedSharedOutputs() throws { + let f = try UpdateFixture(scope: .user) + let extra = f.root.appendingPathComponent("extra") + try f.write( + "---\ndescription: Selected section.\n---\n\n# Extra section\n\nNew contribution.\n", + to: extra.appendingPathComponent("instructions/extra.md")) + var sections = InstructionsDeclaration() + sections.sectionReferences = [ + .init( + name: "rules", source: "fixture", + recipients: [.local(.antigravity), .local(.codex), .chatGPTApp]) + ] + let initial = Declaration( + sources: [ + "fixture": .init(kind: .local, location: f.repo.path), + "extra": .init(kind: .local, location: extra.path), + ], instructions: sections) + try f.store.save(declaration: initial, ledger: ResolvedLedger()) + let initialReport = try f.apply().report + let initialCopy = try #require( + initialReport.instructions.outputs.first { $0.recipient == .chatGPTApp }) + let pinned = try f.store.loadLedger() + let rule = try #require(pinned.deployments.first { $0.recipients == [.antigravity] }) + let ruleURL = try rule.target.resolve(roots: f.store.ledgerRoots) + let initialRule = try f.bytes(ruleURL) + let legacy = try embeddedRuleLock(pinned, repository: f.repo) + let native = try #require(legacy.lowerings.firstIndex { $0.format == "agents/instructions@1" }) + let deployment = try #require( + legacy.deployments.firstIndex { legacy.lowerings[native].deployments.contains($0.id) }) + let copyIndex = try #require( + legacy.lowerings.firstIndex { $0.format == LockedLowering.instructionCopyFormat }) + + func rejects(_ ledger: ResolvedLedger, _ request: UpdateRequest) throws { + try f.store.save(declaration: initial, ledger: ledger) + let before = try f.bytes(f.store.resolvedURL) + #expect { + try UpdateOperations.preview(request, scope: .user, environment: f.environment) + } throws: { error in + String(describing: error).contains("requiresCombinedUpdate") + } + #expect(try f.bytes(f.store.resolvedURL) == before) + } + + var altered = legacy + altered.lowerings[native].layout.object?["headingOffset"] = .init(integer: 1) + try rejects(altered, .init(kinds: [.skills])) + altered = legacy + altered.deployments[deployment].expectedHash = "sha256:" + String(repeating: "0", count: 64) + try rejects(altered, .init(kinds: [.skills])) + + sections.sectionReferences.append( + .init(name: "extra", source: "extra", recipients: [.chatGPTApp])) + func request(_ sections: InstructionsDeclaration) throws -> UpdateRequest { + var changed = initial + try changed.setInstructions(sections) + return .init(operation: .declaration(changed), kinds: [.instructions], names: ["extra"]) + } + let selected = try request(sections) + altered = legacy + altered.lowerings[copyIndex].layout.object?["headingOffset"] = .init(integer: 1) + try rejects(altered, selected) + sections.sectionReferences[0].recipients = [.local(.antigravity), .local(.codex)] + try rejects(legacy, request(sections)) + + let plan = try UpdateOperations.preview(selected, scope: .user, environment: f.environment) + let copy = try #require(plan.instructions.outputs.first { $0.recipient == .chatGPTApp }) + let output = String(decoding: copy.content, as: UTF8.self) + #expect(output.hasPrefix(String(decoding: initialCopy.content, as: UTF8.self))) + #expect(output.contains("New contribution.")) + try apply(f, request: selected, preview: plan) + let updated = try #require( + f.store.loadLedger().lowerings.first { $0.format == LockedLowering.instructionCopyFormat }) + #expect(updated.inputs.count == 2 && updated.layout.object?["sectionCount"]?.integer == 2) + #expect(try f.bytes(ruleURL) == initialRule) + } + + @Test(arguments: [false, true]) + func marketplaceLockProvesLegacyRuleBeforeFreezing(_ alterRule: Bool) throws { + let f = try UpdateFixture(scope: .user) + try declare(f, name: "rules", agents: [.antigravity, .codex, .claudeCode]) + _ = try f.apply() + var declaration = try f.store.loadDeclaration() + let legacy = try embeddedRuleLock(f.store.loadLedger(), repository: f.repo) + let protectedRule = try #require(legacy.deployments.first { $0.recipients == [.antigravity] }) + let ruleURL = try protectedRule.target.resolve(roots: f.store.ledgerRoots) + let originalRule = try f.bytes(ruleURL) + if alterRule { + declaration.components[0] = .instructions( + .init(agents: [.antigravity], sections: ["fixture:rules"])) + } + try f.store.save(declaration: declaration, ledger: legacy) + + let author = try UpdateFixture() + try author.write( + "---\ndescription: Team.\n---\n\n# Team\n\nTeam contribution.\n", + to: author.repo.appendingPathComponent("instructions/rules.md")) + try author.write( + String(contentsOf: f.repo.appendingPathComponent("instructions/rules.md"), encoding: .utf8), + to: author.repo.appendingPathComponent("skills/demo/rule-copy.md")) + try author.commit() + try author.store.save( + declaration: Declaration( + sources: ["fixture": .init(kind: .local, location: author.repo.path)], + skills: ["fixture": .init(select: .all, agents: [.codex], mode: .copy)], + instructions: .init(agents: [.codex, .claudeCode], sections: ["fixture:rules"])), + ledger: ResolvedLedger()) + _ = try author.apply() + let inventory = try UpdateOperations.inspect(environment: author.environment) + let selections = inventory.components.filter { [.instructions, .skills].contains($0.kind) } + .map(\.selection) + let archive = try BundleOperations.export( + .init(name: "team", version: "1.0.0"), selections: selections, + scope: .project, environment: author.environment) + let catalog = author.root.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + try MarketplaceOperations.publishBundle(archive, to: catalog) + let origin = try MarketplaceOrigin(kind: .directory, location: catalog.path) + let members = try BundleOperations.inspect(archive).components + let root = try MarketplaceRoot( + name: "team", catalog: origin, package: "team", requirement: .exact("1.0.0"), + selections: try members.map { + try .init( + package: "team", member: $0.marketplaceKey, + targets: $0.kind == .instructions ? [.codex, .claudeCode] : [.codex]) + }) + if alterRule { + do { + _ = try MarketplaceOperations.previewLockOnly( + .install(root), scope: .user, environment: f.environment) + Issue.record("Accepted a changed protected Antigravity contribution") + } catch let error as CoreError { + #expect(error.description.contains("requiresCombinedUpdate")) + } + } else { + let before = try [.codex, .claudeCode].map { try f.bytes(f.instruction($0)) } + let preview = try MarketplaceOperations.previewLockOnly( + .install(root), scope: .user, environment: f.environment) + try MarketplaceOperations.writeLockOnly(preview) + let deployed = try f.store.loadLedger() + let pending = try #require(deployed.pendingDeployment) + let desired = try pending.desired(in: deployed) + let shared = Set(legacy.contentObjects.keys).intersection(desired.contentObjects.keys) + #expect(!shared.isEmpty) + for digest in shared { + #expect(desired.contentObjects[digest] == legacy.contentObjects[digest]) + } + let deployment = try MarketplaceOperations.previewFrozenDeployment( + scope: .user, environment: f.environment) + _ = try MarketplaceOperations.deployFrozen(deployment) + for (index, agent) in [AgentID.codex, .claudeCode].enumerated() { + let output = try f.bytes(f.instruction(agent)) + #expect(output != before[index]) + let text = String(decoding: output, as: UTF8.self) + #expect(text.contains("# Rules") && text.contains("# Team")) + } + } + #expect(try f.bytes(ruleURL) == originalRule) + } + + private func embeddedRuleLock(_ ledger: ResolvedLedger, repository: URL) throws -> ResolvedLedger + { + var legacy = ledger + var inputs: [String: String] = [:] + for (id, var resource) in ledger.resources where resource.kind == .git { + let file = repository.appendingPathComponent(resource.path) + let contents = try LedgerResources.capture( + file, embed: true, limits: .standard, sourceRoot: repository) + resource.kind = .embedded + resource.entries = contents.entries + resource.support = contents.support + let old = try ResolvedLedgerCodec.digest(resource) + inputs[id] = old + legacy.resources[id] = nil + legacy.resources[old] = resource + legacy.contentObjects.merge(contents.objects) { known, _ in known } + } + var owners: [String: String] = [:] + for (id, var component) in ledger.components { + component.resources = component.resources.map { inputs[$0] ?? $0 } + let old = try ResolvedLedgerCodec.digest(component) + owners[id] = old + legacy.components[id] = nil + legacy.components[old] = component + } + for index in legacy.occurrences.indices { + let owner = legacy.occurrences[index].component + legacy.occurrences[index].component = owners[owner] ?? owner + } + for index in legacy.deployments.indices { + legacy.deployments[index].owners = legacy.deployments[index].owners.map { owners[$0] ?? $0 } + } + for index in legacy.lowerings.indices { + legacy.lowerings[index].inputs = legacy.lowerings[index].inputs.map { owners[$0] ?? $0 } + legacy.lowerings[index].resources = legacy.lowerings[index].resources.map { inputs[$0] ?? $0 } + } + return legacy + } +} diff --git a/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift b/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift index 90a4e03..f61d1a7 100644 --- a/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift +++ b/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift @@ -66,7 +66,7 @@ struct ImportNativeExecutableLifecycleTests { ledger, store: f.store, roots: f.store.ledgerRoots, limits: .standard ) { _, resources, _ in let programID = try #require(record.resources.first) - let program = try #require(resources[programID]) + let program = try #require(resources.files[programID]) #expect(try String(contentsOf: program, encoding: .utf8) == "Frozen executable bytes\n") let mode = try FileManager.default.attributesOfItem(atPath: program.resolvingSymlinksInPath().path)[ @@ -79,7 +79,7 @@ struct ImportNativeExecutableLifecycleTests { } if gemini { #expect(record.resources.count == 2) - let directory = try #require(resources[record.resources[1]]) + let directory = try #require(resources.files[record.resources[1]]) #expect( try String(contentsOf: directory.appendingPathComponent("config.txt"), encoding: .utf8) == "Working directory support") diff --git a/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift b/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift index 201179d..138332b 100644 --- a/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift +++ b/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift @@ -290,6 +290,9 @@ struct NativeAuthorityIntegrationTests { var original = try Data(contentsOf: f.store.resolvedURL) original.append(Data("\n \n".utf8)) try original.write(to: f.store.resolvedURL) + let inode = + try FileManager.default.attributesOfItem(atPath: f.store.resolvedURL.path)[ + .systemFileNumber] as? NSNumber let inspection = try UpdateOperations.inspect(environment: f.environment) let target = try #require(inspection.deployments.first?.location) let output = try Data(contentsOf: target) @@ -297,19 +300,26 @@ struct NativeAuthorityIntegrationTests { _ = try UpdateOperations.restore(environment: f.environment) #expect(try Data(contentsOf: target) == output) #expect(try Data(contentsOf: f.store.resolvedURL) == original) + #expect( + try FileManager.default.attributesOfItem(atPath: f.store.resolvedURL.path)[.systemFileNumber] + as? NSNumber == inode) } @Test func generatedPrivatePluginUsesProductionBindingsAndRetainsFrozenTree() throws { let f = try UpdateFixture() let source = f.root.appendingPathComponent("bundle") + // Replay stores this executable directly under its workspace despite the authored depth. + let depth = FileManager.default.temporaryDirectory.pathComponents.count + 2 + let executable = Array(repeating: "bin", count: depth).joined(separator: "/") + "/server" + let program = source.appendingPathComponent(executable) try f.write( - #"{"name":"upstream","mcpServers":{"native":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/server","env":{"TOKEN":"source-private-canary"}}}}"#, + #"{"name":"upstream","mcpServers":{"native":{"command":"${CLAUDE_PLUGIN_ROOT}/\#(executable)","env":{"TOKEN":"source-private-canary"}}}}"#, to: source.appendingPathComponent(".claude-plugin/plugin.json")) try f.write( "#!/bin/sh\n# fixture source; never executed\n", - to: source.appendingPathComponent("bin/server")) + to: program) try FileManager.default.setAttributes( - [.posixPermissions: 0o755], ofItemAtPath: source.appendingPathComponent("bin/server").path) + [.posixPermissions: 0o755], ofItemAtPath: program.path) try f.store.save( declaration: Declaration(components: [ .plugin( @@ -330,6 +340,10 @@ struct NativeAuthorityIntegrationTests { environment: f.environment, bindingProvider: Bindings(value: "actual-generated-private-canary") ) { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) } + #expect( + try f.store.readLedger().resources.values.contains { + $0.kind == .embedded && $0.support.isEmpty && $0.path.hasSuffix(executable) + }) let snapshot = try UpdateOperations.inspect(environment: f.environment) #expect(snapshot.deployments.allSatisfy { $0.status == .current }) let plugin = try #require(snapshot.components.first { $0.kind == .plugin }) diff --git a/Tests/AgentsUpdatesTests/ScopedPinPublicationTests.swift b/Tests/AgentsUpdatesTests/ScopedPinPublicationTests.swift new file mode 100644 index 0000000..ec52dcb --- /dev/null +++ b/Tests/AgentsUpdatesTests/ScopedPinPublicationTests.swift @@ -0,0 +1,412 @@ +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Scoped pin publication") +struct ScopedPinPublicationTests { + @Test(arguments: [ + TransactionCheckpoint.copy( + 0, .init(path: TransactionSlot.staged.name(0), step: .directoryCreated) + ).name, + TransactionCheckpoint.copy( + 0, .init(path: TransactionSlot.staged.name(0) + "/instructions.md", step: .entryCopied) + ).name, + TransactionCheckpoint.progress(0, .ready).name, + TransactionCheckpoint.publication(0, .created).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + ]) + func interruptedRestoreRecoversAndRetries(_ checkpoint: String) throws { + let fixture = try UpdateFixture() + let source = fixture.repo + let payload = Data("pinned content".utf8) + try payload.write(to: source.appendingPathComponent("instructions.md")) + try fixture.commit() + let revision = try fixture.git(["rev-parse", "HEAD"]) + let environment = fixture.environment + let store = fixture.store + let sourceID = try SourceDeclaration(kind: .local, location: source.path).identity( + environment: environment) + let destination = SourceCache(store: store).materializedURL( + sourceID: sourceID, revision: revision) + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .local, location: .init(kind: .absolute, path: source.path), revision: revision) + ledger.resources["resource"] = .init( + kind: .git, source: "source", path: "instructions.md", + hash: "sha256:" + FileHash.sha256Hex(data: payload), + entries: [.init(path: ".", kind: .file, executable: false, byteCount: payload.count)]) + try store.save(declaration: Declaration(), ledger: ledger) + let original = try Data(contentsOf: store.resolvedURL) + let child = try launch(fixture, command: "cache-git", argument: checkpoint) + defer { terminate(child) } + try waitFor("ready", fixture: fixture, child: child) + terminate(child) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { + try store.withLock {} + } + try UpdateOperations.withPreparedUpdate(.init(operation: .restore), environment: environment) { + _ = try $0.apply() + } + #expect(try Data(contentsOf: destination.appendingPathComponent("instructions.md")) == payload) + #expect(try Data(contentsOf: store.resolvedURL) == original) + } +} + +extension ScopedPinPublicationTests { + @Test func combinedShrinksLegacyPinAndRestoresOnlyMissingPin() throws { + let fixture = try UpdateFixture() + try fixture.install(mode: .link, agents: [.codex]) + let revision = try fixture.git(["rev-parse", "HEAD"]) + let source = SourceDeclaration(kind: .local, location: fixture.repo.path) + let identity = try source.identity(environment: fixture.environment) + let root = SourceCache(store: fixture.store).materializedURL( + sourceID: identity, revision: revision) + let ledger = try FileSnapshot.read(at: fixture.store.resolvedURL) + let target = try FileSnapshot.read(at: fixture.target()) + var limits = LedgerLimits.standard + limits.resourceBytes = 128 * 1024 + let preview = try FileSnapshot.$captureLimits.withValue(limits) { + let old = root.appendingPathComponent("legacy-large") + try Data([0]).write(to: old) + let file = try FileHandle(forWritingTo: old) + try file.truncate(atOffset: UInt64(limits.resourceBytes) + 1) + try file.close() + let filtered = try UpdateOperations.preview( + .init(kinds: [.instructions]), environment: fixture.environment) + #expect(!filtered.hasChanges) + #expect(FileManager.default.fileExists(atPath: old.path)) + let preview = try fixture.preview() + #expect(preview.hasChanges) + var points: [String] = [] + try UpdateOperations.withPreparedUpdate( + environment: fixture.environment, checkpoint: { points.append($0) }, + { _ = try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) }) + #expect(!FileManager.default.fileExists(atPath: old.path)) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == ledger) + #expect(try FileSnapshot.read(at: fixture.target()) == target) + #expect(points.filter { $0.hasPrefix("entry.") && $0.hasSuffix(".ready") }.count == 1) + #expect(!points.contains { $0.contains("objects.synced") }) + return preview + } + let healthy = try fixture.preview() + #expect(!healthy.hasChanges) + #expect(healthy.displayedFingerprint != preview.displayedFingerprint) + + try FileManager.default.removeItem(at: root) + let missing = UpdateRequest(operation: .restore, offline: true) + let restore = try UpdateOperations.preview(missing, environment: fixture.environment) + #expect(restore.hasChanges) + try UpdateOperations.withPreparedUpdate(missing, environment: fixture.environment) { + _ = try $0.apply(ifUnchangedFrom: restore.displayedFingerprint) + } + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == ledger) + #expect(try FileSnapshot.read(at: fixture.target()) == target) + #expect(!(try UpdateOperations.preview(missing, environment: fixture.environment)).hasChanges) + } + + @Test func filteredInstructionUpdateAcceptsEditedRootSkill() throws { + let fixture = try UpdateFixture() + let live = fixture.root.appendingPathComponent("live") + let skill = live.appendingPathComponent("SKILL.md") + try fixture.write("---\nname: live\ndescription: live\n---\n\nold\n", to: skill) + let declaration = Declaration( + sources: [ + "skills": .init(kind: .local, location: live.path), + "rules": .init(kind: .local, location: fixture.repo.path), + ], + skills: ["skills": .init(select: .all, agents: [.codex], mode: .edit)], + instructions: .init(agents: [.codex], sections: ["rules:rules"])) + try fixture.store.save(declaration: declaration, ledger: .init()) + _ = try fixture.apply() + let target = AgentRegistry.installSkillsDirectory( + for: .codex, scope: .project, environment: fixture.environment + ).appendingPathComponent("live") + let installed = try FileSnapshot.read(at: target) + try fixture.write("---\nname: live\ndescription: live\n---\n\nnew\n", to: skill) + try fixture.advance() + let request = UpdateRequest(kinds: [.instructions]) + let preview = try UpdateOperations.preview(request, environment: fixture.environment) + try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + _ = try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(try FileSnapshot.read(at: target) == installed) + #expect( + try String(contentsOf: target.appendingPathComponent("SKILL.md"), encoding: .utf8).contains( + "new")) + } +} + +extension ScopedPinPublicationTests { + @Test(arguments: [false, true]) + func frozenDeploymentAuthenticatesRetainedPathsBeforeGrowingThePin(_ tampered: Bool) throws { + let f = try UpdateFixture() + let candidate = try UpdateFixture() + try f.write( + "---\ndescription: Additional instructions.\n---\n\n# More\n\nFrozen pin growth content.\n", + to: f.repo.appendingPathComponent("instructions/more.md")) + try f.commit() + try f.install(mode: .link, agents: [.codex]) + let source = SourceDeclaration(kind: .local, location: f.repo.path) + let desired = Declaration( + sources: ["fixture": source], + skills: ["fixture": .init(select: .all, agents: [.codex], mode: .link)], + instructions: .init(agents: [.codex], sections: ["fixture:more"])) + try candidate.store.save(declaration: desired, ledger: ResolvedLedger()) + _ = try candidate.apply() + var deployed = try f.store.loadLedger() + try f.store.save(declaration: desired, ledger: deployed) + let declaration = try f.bytes(f.store.declarationURL) + deployed.pendingDeployment = try MarketplacePendingDeploymentRecord( + ledger: candidate.store.loadLedger(), deployed: deployed, + declarationDigest: "sha256:" + FileHash.sha256Hex(data: declaration)) + try f.store.save(declaration: desired, ledger: deployed) + let revision = try f.git(["rev-parse", "HEAD"]) + let pin = SourceCache(store: f.store).materializedURL( + sourceID: try source.identity(environment: f.environment), revision: revision) + let oldPath = pin.appendingPathComponent("skills/demo/SKILL.md") + let newPath = pin.appendingPathComponent("instructions/more.md") + #expect(!FileManager.default.fileExists(atPath: newPath.path)) + if tampered { + try f.write("outside edit", to: oldPath) + let lock = try f.bytes(f.store.resolvedURL) + do { + _ = try MarketplaceOperations.previewFrozenDeployment(environment: f.environment) + Issue.record("Accepted changed retained skill bytes") + } catch let error as CoreError { + #expect(error.description.contains("skills/demo")) + } + #expect(try f.bytes(oldPath) == Data("outside edit".utf8)) + #expect(try f.bytes(f.store.resolvedURL) == lock) + #expect(!FileManager.default.fileExists(atPath: newPath.path)) + } else { + let original = try f.bytes(oldPath) + let preview = try MarketplaceOperations.previewFrozenDeployment(environment: f.environment) + _ = try MarketplaceOperations.deployFrozen(preview) + #expect(try f.bytes(oldPath) == original) + #expect( + try f.bytes(newPath) == f.bytes(f.repo.appendingPathComponent("instructions/more.md"))) + let active = try f.store.loadLedger() + #expect(active.pendingDeployment == nil) + #expect( + active.resources.values.contains { $0.kind == .git && $0.path == "instructions/more.md" }) + } + } + + @Test func internalSymlinkKeepsLegacySupportShapeInWarmAndColdRestore() throws { + let f = try UpdateFixture() + let folder = f.repo.appendingPathComponent("skills/demo") + try f.write("reference", to: folder.appendingPathComponent("README.md")) + try FileManager.default.createSymbolicLink( + atPath: folder.appendingPathComponent("guide").path, withDestinationPath: "README.md") + try f.commit() + try f.install(mode: .link, agents: [.codex]) + let ledger = try f.store.loadLedger() + let resource = try #require(ledger.resources.values.first { $0.path == "skills/demo" }) + #expect(resource.support.isEmpty) + #expect(resource.entries.contains { $0.path == "guide" && $0.link == "README.md" }) + let request = UpdateRequest(operation: .restore, offline: true) + #expect(!(try UpdateOperations.preview(request, environment: f.environment)).hasChanges) + let source = SourceDeclaration(kind: .local, location: f.repo.path) + let pin = SourceCache(store: f.store).materializedURL( + sourceID: try source.identity(environment: f.environment), + revision: try f.git(["rev-parse", "HEAD"])) + try FileManager.default.removeItem(at: pin) + try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + _ = try $0.apply() + } + #expect(try f.bytes(f.target().appendingPathComponent("guide")) == Data("reference".utf8)) + #expect(try f.store.loadLedger() == ledger) + } + + @Test func coldReplayRejectsUncoveredRefDependentSupport() throws { + let f = try UpdateFixture() + let relative = "shared/banner.txt" + try f.write( + "$Format:%<(64,trunc)%(describe:tags=true)$\n", to: f.repo.appendingPathComponent(relative)) + try f.write(relative + " export-subst\n", to: f.repo.appendingPathComponent(".gitattributes")) + try FileManager.default.createSymbolicLink( + atPath: f.repo.appendingPathComponent("skills/demo/banner").path, + withDestinationPath: "../../" + relative) + try f.commit() + try f.git(["tag", "historical"]) + let revision = try f.git(["rev-parse", "HEAD"]) + let archive = f.root.appendingPathComponent("historical.tar") + try f.git(["archive", "--format=tar", "--output=" + archive.path, revision]) + let tree = f.root.appendingPathComponent("historical") + try FileManager.default.createDirectory(at: tree, withIntermediateDirectories: false) + _ = try ProcessRunner.run("/usr/bin/tar", arguments: ["-xf", archive.path, "-C", tree.path]) + let captured = try LedgerResources.capture( + tree.appendingPathComponent("skills/demo"), embed: false, limits: .standard, sourceRoot: tree) + #expect( + captured.support.contains { $0.path == relative && $0.kind == .file && $0.object == nil }) + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .local, location: .init(kind: .absolute, path: f.repo.path), revision: revision) + ledger.resources["skill"] = .init( + kind: .git, source: "source", path: "skills/demo", hash: captured.hash, + entries: captured.entries, support: captured.support) + try f.store.save(declaration: Declaration(), ledger: ledger) + let request = UpdateRequest(operation: .restore, offline: true) + do { + _ = try UpdateOperations.preview(request, environment: f.environment) + Issue.record("Accepted ref-dependent support with only coordinate evidence") + } catch let error as UnverifiableGitArchive { + #expect(error.path == relative && error.revision == revision) + } + let historic = try f.bytes(tree.appendingPathComponent(relative)) + #expect(String(decoding: historic, as: UTF8.self).contains("historical")) + ledger.resources["covering-file"] = .init( + kind: .git, source: "source", path: relative, + hash: "sha256:" + FileHash.sha256Hex(data: historic), + entries: [.init(path: ".", kind: .file, executable: false, byteCount: historic.count)]) + try f.store.save(declaration: Declaration(), ledger: ledger) + try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + _ = try $0.apply() + } + let source = SourceDeclaration(kind: .local, location: f.repo.path) + let pin = SourceCache(store: f.store).materializedURL( + sourceID: try source.identity(environment: f.environment), revision: revision) + let retained = pin.appendingPathComponent(relative) + #expect(try f.bytes(retained) == historic) + #expect(!(try UpdateOperations.preview(request, environment: f.environment)).hasChanges) + var edited = historic + edited[edited.startIndex] ^= 1 + try edited.write(to: retained) + #expect { + try UpdateOperations.preview(request, environment: f.environment) + } throws: { error in + String(describing: error).contains("locked resource content or execute bits changed") + } + } + + @Test func historicalArchiveMustMatchTheLockedHash() throws { + let fixture = try UpdateFixture() + let relative = "legacy.txt" + try fixture.write( + "$Format:%(describe:tags=true)$\n", to: fixture.repo.appendingPathComponent(relative)) + try fixture.write( + "legacy.txt export-subst\n", to: fixture.repo.appendingPathComponent(".gitattributes")) + try fixture.commit() + try fixture.git(["tag", "-a", "legacy-release", "-m", "legacy"]) + let revision = try fixture.git(["rev-parse", "HEAD"]) + let archive = fixture.root.appendingPathComponent("legacy.tar") + try fixture.git(["archive", "--format=tar", "--output=" + archive.path, revision]) + let extracted = fixture.root.appendingPathComponent("historical") + try FileManager.default.createDirectory(at: extracted, withIntermediateDirectories: false) + _ = try ProcessRunner.run( + "/usr/bin/tar", arguments: ["-xf", archive.path, "-C", extracted.path]) + let bytes = try Data(contentsOf: extracted.appendingPathComponent(relative)) + #expect(String(decoding: bytes, as: UTF8.self).contains("legacy-release")) + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .local, location: .init(kind: .absolute, path: fixture.repo.path), revision: revision) + ledger.resources["legacy"] = .init( + kind: .git, source: "source", path: relative, + hash: "sha256:" + FileHash.sha256Hex(data: bytes), + entries: [.init(path: ".", kind: .file, executable: false, byteCount: bytes.count)]) + try fixture.store.save(declaration: Declaration(), ledger: ledger) + try fixture.git(["tag", "-d", "legacy-release"]) + let request = UpdateRequest(operation: .restore, offline: true) + #expect(throws: CoreError.self) { + try UpdateOperations.preview(request, environment: fixture.environment) + } + try fixture.git(["tag", "-a", "legacy-release", "-m", "legacy"]) + try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + _ = try $0.apply() + } + let source = SourceDeclaration(kind: .local, location: fixture.repo.path) + let identity = try source.identity(environment: fixture.environment) + let pin = SourceCache(store: fixture.store).materializedURL( + sourceID: identity, revision: revision) + #expect(try Data(contentsOf: pin.appendingPathComponent(relative)) == bytes) + } +} + +extension ScopedPinPublicationTests { + @Test func liveDescendantVetoesBothPinGrowthAndRetirement() throws { + let f = try UpdateFixture() + try f.write( + "---\ndescription: Additional instructions.\n---\n\n# More\n", + to: f.repo.appendingPathComponent("instructions/more.md")) + try f.commit() + try f.install(mode: .link, agents: [.codex]) + let committed = SourceDeclaration(kind: .local, location: f.repo.path) + let identity = try committed.identity(environment: f.environment) + let revision = try f.git(["rev-parse", "HEAD"]) + let pin = SourceCache(store: f.store).materializedURL(sourceID: identity, revision: revision) + let editable = pin.appendingPathComponent("skills/demo") + let live = SourceDeclaration(kind: .local, location: editable.path) + func declaration(_ sections: [String]) -> Declaration { + Declaration( + sources: sections.isEmpty ? ["live": live] : ["fixture": committed, "live": live], + skills: sections.isEmpty + ? ["live": .init(select: .all, agents: [.claudeCode], mode: .edit)] + : [ + "fixture": .init(select: .all, agents: [.codex], mode: .link), + "live": .init(select: .all, agents: [.claudeCode], mode: .edit), + ], + instructions: .init(agents: [.codex], sections: sections)) + } + let establish = UpdateRequest(operation: .declaration(declaration(["fixture:rules"]))) + try UpdateOperations.withPreparedUpdate(establish, environment: f.environment) { + _ = try $0.apply() + } + let pinnedBefore = try FileSnapshot.read(at: pin) + let grow = UpdateRequest( + operation: .declaration(declaration(["fixture:rules", "fixture:more"]))) + do { + _ = try UpdateOperations.preview(grow, environment: f.environment) + Issue.record("A pin with an editable descendant was allowed to grow") + } catch let error as CoreError { + #expect(error.description.contains("overlaps live edit source")) + } + #expect(try FileSnapshot.read(at: pin) == pinnedBefore) + let retire = UpdateRequest(operation: .declaration(declaration([]))) + try UpdateOperations.withPreparedUpdate(retire, environment: f.environment) { + _ = try $0.apply() + } + #expect(try FileSnapshot.read(at: pin) == pinnedBefore) + #expect( + FileManager.default.fileExists(atPath: editable.appendingPathComponent("SKILL.md").path)) + } +} + +extension ScopedPinPublicationTests { + @Test func supportBytesCannotBeReplacedByAnEquallySizedFile() throws { + let f = try UpdateFixture() + let link = f.repo.appendingPathComponent("skills/demo/run.sh") + try FileManager.default.removeItem(at: link) + try FileManager.default.createSymbolicLink( + atPath: link.path, withDestinationPath: "../../shared/run.sh") + try f.write("valid\n", to: f.repo.appendingPathComponent("shared/run.sh")) + try Data(repeating: 42, count: 4 * 1024 * 1024).write( + to: f.repo.appendingPathComponent("shared/unrelated")) + try f.commit() + try f.install(mode: .link, agents: [.codex]) + let identity = try SourceDeclaration(kind: .local, location: f.repo.path) + .identity(environment: f.environment) + let revision = try f.git(["rev-parse", "HEAD"]) + let pin = SourceCache(store: f.store).materializedURL(sourceID: identity, revision: revision) + let retained = pin.appendingPathComponent("shared/run.sh") + #expect( + !FileManager.default.fileExists(atPath: pin.appendingPathComponent("shared/unrelated").path)) + let mode = + try FileManager.default.attributesOfItem(atPath: retained.path)[.posixPermissions] + as? NSNumber + try f.write("wrong\n", to: retained) + #expect( + try FileManager.default.attributesOfItem(atPath: retained.path)[.posixPermissions] + as? NSNumber == mode) + do { + _ = try UpdateOperations.preview( + .init(operation: .restore, offline: true), environment: f.environment) + Issue.record("Replayed modified support bytes") + } catch let error as CoreError { + #expect(error.description.contains("shared/run.sh")) + } + #expect(try String(contentsOf: retained, encoding: .utf8) == "wrong\n") + } +} diff --git a/Tests/ComponentsTests/PluginLinkingTests.swift b/Tests/ComponentsTests/PluginLinkingTests.swift index 94fe6bd..2d0135f 100644 --- a/Tests/ComponentsTests/PluginLinkingTests.swift +++ b/Tests/ComponentsTests/PluginLinkingTests.swift @@ -1,8 +1,9 @@ import AgentsCore -import Components import Foundation import Testing +@testable import Components + @Suite("Plugin occurrence linking", .serialized) struct PluginLinkingTests { private func container(_ fixture: LinkFixture, _ path: String, at root: URL) throws { @@ -137,6 +138,52 @@ struct PluginLinkingTests { #expect(decoded.occurrences == ledger.occurrences) } + @Test(arguments: [false, true]) + func pluginDiscoverySkipsLinkWithExportIgnoredTarget(_ warm: Bool) throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("producer") + try fixture.initialize(repository) + let claude = "review/.claude-plugin/plugin.json" + try fixture.write(#"{"name":"review"}"#, to: claude, base: repository) + try fixture.write( + #"{"name":"hidden","version":"1.0.0"}"#, to: "review/hidden.json", base: repository) + try fixture.write("review/hidden.json export-ignore\n", to: ".gitattributes", base: repository) + try FileManager.default.createSymbolicLink( + atPath: repository.appendingPathComponent("review/gemini-extension.json").path, + withDestinationPath: "hidden.json") + try FileManager.default.createSymbolicLink( + atPath: repository.appendingPathComponent("review/plugin.json").path, + withDestinationPath: "hidden.json") + let revision = try fixture.commit(repository) + let source = SourceDeclaration( + kind: .local, location: repository.path, requirement: .revision(revision)) + let document = try fixture.document( + """ + version: 1 + sources: {p: {path: "\(repository.path)", requirement: {revision: "\(revision)"}}} + components: [{kind: plugin, name: review, path: review, source: p, select: []}] + """) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let pin = SourceRevision(revision: revision) + let view = try session.snapshot(source, at: pin) + let gemini = view.root.appendingPathComponent("review/gemini-extension.json") + if warm { + _ = try view.directory() + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: gemini.path) == "hidden.json") + } + let linker = Linking( + document: document, store: fixture.store, platform: .macOS, + session: session, directPins: [:], retainedLedger: nil) + let graph = try linker.solve(preserving: [view.snapshot.source: pin]) + let plugin = try #require(graph.components.first { $0.key.kind == .plugin }) + #expect(plugin.origins.first?.pluginExpansion?.document == claude) + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: gemini.path) == "hidden.json") + #expect(!FileManager.default.fileExists(atPath: gemini.path)) + } + } + @Test func memberIdentityDoesNotInheritDeclaringParentGroup() throws { let fixture = try LinkFixture() try container(fixture, "one", at: fixture.project) diff --git a/Tests/ComponentsTests/SourceCatalogTests.swift b/Tests/ComponentsTests/SourceCatalogTests.swift index 01b3dca..58f9034 100644 --- a/Tests/ComponentsTests/SourceCatalogTests.swift +++ b/Tests/ComponentsTests/SourceCatalogTests.swift @@ -253,8 +253,10 @@ struct SourceCatalogTests { } extension SourceCatalogTests { - @Test func portableManifestRecordsItsOwnAdapterAndMetadata() throws { + @Test(arguments: [false, true]) + func portableManifestRecordsItsOwnAdapterAndMetadata(_ git: Bool) throws { let fixture = try LinkFixture() + if git { try fixture.initialize(fixture.project) } try fixture.write( """ {"$schema":"\(AgentPluginManifest.schema)","name":"portable","version":"1.2.3", @@ -263,6 +265,18 @@ extension SourceCatalogTests { try fixture.write( "---\nname: review\ndescription: Review skill\n---\nBody\n", to: "bundle/skills/review/SKILL.md", base: fixture.project) + if git { + try fixture.write( + "bundle/hidden-marketplace.json export-ignore\n", to: ".gitattributes", + base: fixture.project) + try fixture.write("{}", to: "bundle/hidden-marketplace.json", base: fixture.project) + let directory = fixture.project.appendingPathComponent("bundle/.agents/plugins") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: directory.appendingPathComponent("marketplace.json").path, + withDestinationPath: "../../hidden-marketplace.json") + try fixture.commit(fixture.project) + } let catalog = try inspect(fixture, path: "bundle") let components = catalog.choices.filter { if case .componentsPlugin = $0.unit { true } else { false } diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 3b014fe..76072b0 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -40,6 +40,14 @@ if arguments[2] == "open-file-limit" { try openFileLimitProbe(arguments[3], root: root, store: store) exit(EXIT_SUCCESS) } +if arguments[2] == "inspect-local-expression" { + let source = SourceDeclaration( + kind: .local, location: root.appendingPathComponent("producer").path, + requirement: .revision(arguments[3])) + let pin = try SourceCache(store: store).inspectRevision(source) + try Data(pin.revision.utf8).write(to: root.appendingPathComponent("selected-revision")) + exit(EXIT_SUCCESS) +} let checkpointState = Mutex( (requested: arguments.count > 3 ? arguments[3] : "", seen: Set())) let traceURL = root.appendingPathComponent( @@ -123,6 +131,10 @@ if arguments[2].hasPrefix("acquisition-") { default: fatalError("unknown acquisition test operation") } +} else if arguments[2] == "cache-git" { + try UpdateOperations.withPreparedUpdate( + .init(operation: .restore), scope: scope, environment: store.environment, + checkpoint: { try stop($0) }, { _ = try $0.apply() }) } else if arguments[2] == "source-archive" { try sourceArchiveProbe( root: root, input: URL(fileURLWithPath: arguments[4]), checkpoint: { try stop($0) }) @@ -423,13 +435,10 @@ if arguments[2].hasPrefix("acquisition-") { try store.withLock( footprint: createdSkill?.footprint ?? [], installations: createdSkill.map { [$0] } ?? [] ) { - if arguments[2] == "cache-content" || arguments[2] == "cache-git" - || arguments[2] == "cache-bytes" - { + if arguments[2] == "cache-content" || arguments[2] == "cache-bytes" { let cache = SourceCache(store: store) { try stop($0) } let ledger = try store.readLedger() - guard let resource = ledger.resources["resource"], - let source = ledger.sources[resource.source] + guard let resource = ledger.resources["resource"] else { throw CoreError.invalidState("missing fixture resource") } @@ -439,10 +448,6 @@ if arguments[2].hasPrefix("acquisition-") { } else if arguments[2] == "cache-bytes", let artifact = resource.artifact { _ = try cache.storeArtifact( Data(contentsOf: root.appendingPathComponent("payload")), digest: artifact.digest) - } else if let location = source.location { - let identity = "local:" + (try location.resolve(roots: store.ledgerRoots).path) - _ = try cache.materialize( - sourceID: identity, source: LockedSource(kind: .local), revision: source.revision) } else { throw CoreError.invalidState("missing fixture pin") }